Dictionaries Assemble
Published on Dec 10, 2019Dictionaries Assemble — SwiftMoji Entry #14
The Dictionary is Swift’s data structure for mapping unique keys to corresponding values. They are an optimal solution for recording important metadata about the members of a set. In the code example, 👥Present records the attendance of each individual in a role call. Unfortunately, the unordered nature of Dictionaries becomes problematic when iterating through the names in 👥Present in alphabetical order. This can be accomplished by calling the sorted(by:) method with a key-value comparison closure parameter called areInIncreasingOrder. The closure in the example uses the < operator between the two incoming keys because the names in 👥Present need to be called alphabetically. The return type of sorted(by:) is an Array of key-value tuples. This can be directly inserted into a for-in loop for easy iteration.
var 👥Present = [
"Allegra Love": false,
"Azeem Bell": false,
"Adina Williamson": false,
"Niall Lim": false,
"Asiyah Fuentes": false
]
for 👤 in 👥Present.sorted(by: { $0.key < $1.key }) {
let name = 👤.key
print("\(name) is here.")
👥Present[name] = true
}
// Adina Williamson is here.
// Allegra Love is here.
// Asiyah Fuentes is here.
// Azeem Bell is here.
// Niall Lim is here.
Tagged with: