NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How are tuples different from arrays in Swift?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

When you’re learning Swift tuples and arrays can seem like they are the same thing, but really they couldn’t be much more different.

Both tuples and arrays allow us to hold several values in one variable, but tuples hold a fixed set of things that can’t be changed, whereas variable arrays can have items added to them indefinitely.

For example, if we wanted a variable tuple to store a website, we might write this:

var website = (name: "Apple", url: "")

If we wanted to add to that the date we last visited the site, we couldn’t – it’s two string items, name and url, nothing more. Because they are specific and named, Swift lets us read them back as and website.url.

In comparison, if we wanted an array instead we might have written this:

var website = ["Apple", ""]

That no longer has names, so we need to read the values using integers: website[0] and website[1]. We can also add more things to it freely, because it’s a variable array – it can hold any number of strings, rather than just the two we specified.

Another advantage to tuples is that each value is specifically created by you, so as well as providing a name you also provide a type. So, you could create a tuple like this one:

var person = (name: "Paul", age: 40, isMarried: true)

That combines a string, an integer, and a Boolean in a single value, which would be pretty ugly in an array.

Dictionaries provide an interesting third case, because they give us some of the name safety of tuples but can grow and change like arrays. I say “some of the name safety” because we can’t guarantee that a particular value exists in a dictionary like we can with a tuple – we just need to try reading it and handle the optional that comes back.

Hacking with Swift is sponsored by Waldo

SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.

Try for free today!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.