- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swift Program to Sort Dictionary by keys
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 their keys.
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 keys.
Step 4 − Display the final output.
Example
In the following Swift program, we are going to sort a dictionary by keys. So first create a dictionary. Then pass this closure ({ $0.key < $1.key }) in the sorted(by:) function to sort the elements of the dictionary according to the key 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": "Mona", "company": "XMK.pvt", "city": "Mumbai"] print("Original dictionary:", myDict) let Sdict = myDict.sorted(by: { $0.key < $1.key }) print("Sorted dictionary:", Sdict)
Output
Original dictionary: ["city": "Mumbai", "name": "Mona", "company": "XMK.pvt"] Sorted dictionary: [(key: "city", value: "Mumbai"), (key: "company", value: "XMK.pvt"), (key: "name", value: "Mona")]
Conclusion
So this is how we can sort dictionaries by keys. The sorted() method returns accurate results. Also, it does not modify the original dictionary instead it creates a new dictionary which contains the result. And the complexity of the sorted(by:) method is O(n log n) where n is the length of the dictionary.