NEW! Master Swift design patterns with my latest book! >>

How to use the zip() function to join two arrays

Paul Hudson       @twostraws

The zip() function is designed to merge two sequences into a single sequence of tuples. For example, here is an array of wizards:

let wizards = ["Harry", "Ron", "Hermione"]

And here’s a matching array of the animals owned by those wizards:

let animals = ["Hedwig", "Scabbers", "Crookshanks"]

Using zip() we can combine them together:

let combined = zip(wizards, animals)

That will produce a single sequence combining the earlier two. To avoid doing extra work, Swift actually creates a special type called Zip2Sequence that stores both sequences internally – this is more efficient than doing the actual joining, but it does make the output harder to read if you’re using a playground. So, if you are using a playground you should wrap the output from zip() into a new array to make its output easier to read:

let combined = Array(zip(wizards, animals))

If you print combined you’ll see it contains this array:

[("Harry", "Hedwig"), ("Ron", "Scabbers"), ("Hermione", "Crookshanks")]

One of the helpful features of zip() is that if your two arrays differ in size it will automatically choose the shorter of the two. This avoids trying to read two arrays at the same time and accidentally going out of bounds when one is shorter.

For example, this code will print out the animals belonging to the first three wizards, but nothing for Draco because he doesn’t have a matching animal:

let wizards = ["Harry", "Ron", "Hermione", "Draco"]
let animals = ["Hedwig", "Scabbers", "Crookshanks"]

for (wizard, animal) in zip(wizards, animals) {
    print("\(wizard) has \(animal)")
}

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Get my latest video for free

Learn about value types, functional programming, and protocol-oriented programming in this new video – it's free!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>