Grant Emerson

Merging Food With Thought

Merging Food With Thought — SwiftMoji Entry #25

Swift provides the Dictionary data structure as a way to store key-value pairs. Sometimes two Dictionaries contain semantically related data. The merge(_:uniquingKeysWith:) instance method can be used to combine their contents. The first parameter is labeled other and simply provides the Dictionary to be merged with. One of the defining characteristics of a Dictionary is its strict policy of prohibiting duplicate keys. To enforce this rule, the merging method takes in a combine closure. The closure takes in two values and returns one value that is the same type as the original dictionary values. In the code example, shorthand argument names $0 and $1 are used to return the summation of the total amount of times a food was eaten throughout the Saturday and Sunday logs.

let saturdayFoodLog = ["🍎": 2, "🥗": 2, "🥚": 3, "🥜": 20, "🍪": 2]
let sundayFoodLog = ["🥚": 1, "🥗": 1, "🍎": 1, "🍪": 1, "🌭": 2, "🥩": 1]
let weekendFoodLog = saturdayFoodLog.merging(sundayFoodLog) { $0 + $1 }
print(weekendFoodLog) // ["🥩": 1, "🥚": 4, "🥗": 3, "🍎": 3, "🥜": 20, "🌭": 2, "🍪": 3]
Tagged with: