
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Dictionary by Values in Swift
Swift supports a sorted() method to sort all the elements present in the given dictionary. This method sorts the key-value pairs of the dictionary according to the values.
Syntax
func sorted(by:)
Here, the value of by parameters are ?
Greater than(>) ? To sort the elements into descending order.
Less than(<) ? To sort the elements into ascending order.
Closure ? Sort the elements according to the given closure.
Algorithm
Step 1 ? Create a dictionary with key-value pairs.
Step 2 ? Display the original dictionary.
Step 3 ? Now use the sorted() function to sort the key-value pairs according to their values.
Step 4 ? Display the final output.
Example
In the following Swift program, we are going to sort the dictionary by values. So we will create a dictionary. Then pass this closure ({ $0.value < $1.value }) in the sorted(by:) function to sort the elements of the dictionary according to the value and display the final result. Here $0 and $1 represent the first and second parameters passed into the closure.
import Foundation import Glibc let myDict = ["name": "Sona", "company": "MOKA.PVT", "city": "New Delhi"] print("Original dictionary:", myDict) let Sdict = myDict.sorted(by: { $0.value < $1.value }) print("Sorted dictionary:", Sdict)
Output
Original dictionary: ["name": "Sona", "company": "MOKA.PVT", "city": "New Delhi"] Sorted dictionary: [(key: "company", value: "MOKA.PVT"), (key: "city", value: "New Delhi"), (key: "name", value: "Sona")]
Conclusion
So this is how we can sort dictionaries by values. The sorted() method returns accurate results. Also, it does not modify the original dictionary instead it creates a new dictionary which contains the result. The complexity of the sorted(by:) method is O(n log n) where n is the length of the dictionary.