UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How are tuples different from arrays in Swift?

Paul Hudson    @twostraws   

Updated for Xcode 15

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: "www.apple.com")

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 website.name and website.url.

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

var website = ["Apple", "www.apple.com"]

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.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

BUY OUR BOOKS
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.