Grant Emerson

Zip-A-Dee-Doo-Dah Zip-An-Array

Zip-A-Dee-Doo-Dah Zip-An-Array — SwiftMoji Entry #2

Sometimes, two arrays in a program have closely related elements. Accessing these arrays sequentially with the same index throughout a codebase can become a bit verbose. The logical approach to combine the elements from both arrays is to create an array of tuples. In Swift, two Sequences can be combined in this fashion using the zip(_:_:) method. Zip returns a Zip2Sequence instance where each pair corresponds to elements at the same index in the original sequences. The zip(_:_:) method will create the same amount of pairs as the shortest input sequence. Additionally, an Array must be initialized with the contents of a Zip2Sequence to get subscripting. The resulting tuples have default numerical element names that are a bit difficult to work with. In the following code example, this issue is solved by creating a Meal tuple type with element names: drink and food. The result of zipping the drinks and foods String Arrays is then cast to be an Array of the Meal type.

typealias Meal = (drink: String, food: String)

let drinks = ["🥛", "☕️", "🥤", "🍺", "🍷", "🍹"]
let foods = ["🍪", "🥓🍳", "🍔🍟", "🥜", "🍝", "🥗"]
let meals = Array(zip(drinks, foods)) as [Meal]

let dinner = meals[2]
print("Tonight, we will have \(dinner.drink) and \(dinner.food) for dinner.")
// Tonight, we will have 🥤 and 🍔🍟 for dinner.
Tagged with: