Ad space (banner)
๐ŸฆSwift Lessons
Lesson 44 / 68

Pairing Up Two Arrays (the zip operation)

In this lesson you will learn to pair up two arrays with Swift's zip function, so related data can be handled together. This is for anyone searching for "Swift zip how to use".

Combining two corresponding arrays - a list of names and a list of scores, say - into pairs one by one is called a zip operation. Swift has a function named exactly that: zip().

The sample code pairs up the elements at matching positions in names and scores with zip(names, scores), taking them out one at a time with for (name, score) in zip(...).

A common stumbling block for beginners is what happens when the two arrays are different lengths. zip() stops at the shorter one, so any leftovers are simply not included.

In real-world development, nesting zip calls handles three or more arrays.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)