The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).
Example
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()
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
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.