To sort a dictionary by values in Swift, you can use the `sorted(by:)` method and a dictionary comprehension. This allows you to create a new dictionary with the key-value pairs sorted by value.
We can sort a dictionary by values in Swift using the `sorted(by:)` method. This example demonstrates how to declare and initialize a dictionary, use the `sorted(by:)` method to sort the dictionary by values, and print the sorted dictionary.
For example,
myDictionary
with integer keys and string values.var myDictionary: [Int: String] = [
1: "One",
2: "Two",
3: "Three"
]
// Sort the dictionary by values using sorted(by:)
let sortedDict = Dictionary(uniqueKeysWithValues: myDictionary.sorted(by: { $0.value < $1.value }))
// Print the sorted dictionary
print("Sorted dictionary:")
for (key, value) in sortedDict {
print("Key: \(key), Value: \(value)")
}
Sorted dictionary: Key: 1, Value: One Key: 3, Value: Three Key: 2, Value: Two
We can sort a dictionary by values in descending order in Swift using the `sorted(by:)` method. This example demonstrates how to declare and initialize a dictionary, use the `sorted(by:)` method to sort the dictionary by values in descending order, and print the sorted dictionary.
For example,
myDictionary
with integer keys and string values.var myDictionary: [Int: String] = [
1: "One",
2: "Two",
3: "Three"
]
// Sort the dictionary by values in descending order using sorted(by:)
let sortedDict = Dictionary(uniqueKeysWithValues: myDictionary.sorted(by: { $0.value > $1.value }))
// Print the sorted dictionary
print("Sorted dictionary:")
for (key, value) in sortedDict {
print("Key: \(key), Value: \(value)")
}
Sorted dictionary: Key: 2, Value: Two Key: 3, Value: Three Key: 1, Value: One
In this tutorial, we learned How to Sort a Dictionary by Values in Swift language with well detailed examples.