To sort a dictionary by keys 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 key.
We can sort a dictionary by keys 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 keys, and print the sorted dictionary.
For example,
myDictionary
with integer keys and string values.var myDictionary: [Int: String] = [
3: "Three",
1: "One",
2: "Two"
]
// Sort the dictionary by keys using sorted(by:)
let sortedDict = Dictionary(uniqueKeysWithValues: myDictionary.sorted(by: { $0.key < $1.key }))
// Print the sorted dictionary
print("Sorted dictionary:")
for (key, value) in sortedDict {
print("Key: \(key), Value: \(value)")
}
Sorted dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can sort a dictionary by keys 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 keys in descending order, and print the sorted dictionary.
For example,
myDictionary
with integer keys and string values.var myDictionary: [Int: String] = [
3: "Three",
1: "One",
2: "Two"
]
// Sort the dictionary by keys in descending order using sorted(by:)
let sortedDict = Dictionary(uniqueKeysWithValues: myDictionary.sorted(by: { $0.key > $1.key }))
// Print the sorted dictionary
print("Sorted dictionary:")
for (key, value) in sortedDict {
print("Key: \(key), Value: \(value)")
}
Sorted dictionary: Key: 3, Value: Three Key: 2, Value: Two Key: 1, Value: One
In this tutorial, we learned How to Sort a Dictionary by Keys in Swift language with well detailed examples.