Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Swift Dictionary sorted()
In this tutorial, we will learn about the Swift dictionary sorted() method with the help of examples.
The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).
Example
let age = ["Ranjit": 1930, "Sabby": 2008 ]
// sort dictionary by key in ascending order
let sortAge = age.sorted(by: <)
print(sortAge)
// Output: [(key: "Ranjit", value: 1930), (key: "Sabby", value: 2008)]
sorted() Syntax
The syntax of the dictionary sorted() method is:
dictionary.sorted(by: {operator})
Here, dictionary is an object of the dictionary class.
sorted() Parameters
The sorted() method can take one parameter:
- operator (optional) - a closure that accepts a condition and returns a Bool value.
Note: If we pass greater-than operator >, the dictionary is sorted in descending order
sorted() Return Value
The sorted() method returns an array of tuples.
Example 1: Swift dictionary sorted()
var info = ["Carlos": 1999, "Nelson": 1987]
// sort dictionary by key in ascending order
let sortInfo = info.sorted(by: > )
print(sortInfo)
Output
[(key: "Nelson", value: 1987), (key: "Carlos", value: 1999)]
Here, we can see that the info dictionary is sorted by key in ascending order of the string. For example, "Carlos" comes before "Nelson" because "C" comes before "N".
Example 2: Sort by Passing Closure
ley info = ["Carlos": 1999, "Nelson": 1987]
// sort dictionary by value in ascending order
let sortInfo = info.sorted(by: { $0.value < $1.value } )
print(sortInfo)
Output
[(key: "Nelson", value: 1987), (key: "Carlos", value: 1999)]
In the above example, we have passed the closure to sort info by value in ascending order. Notice the closure definition,
{ $0.value < $1.value }
This is a short-hand closure that checks whether the first value of info is less than the second value or not.
$0 and $1 is the shortcut to mean the first and second parameters passed into the closure.