< Why are sets different from arrays in Swift? | When should you use an array, a set, or a tuple in Swift? > |
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: "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.
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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.