|< Why are sets different from arrays in Swift?||When should you use an array, a set, or a tuple in Swift? >|
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,
url, nothing more. Because they are specific and named, Swift lets us read them back as
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. 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 Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.
Link copied to your pasteboard.