Swift version: 5.10
Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to return multiple values from a function call.
You can create a basic tuple like this:
let person = (name: "Paul", age: 35)
As you can see, it looks like an anonymous struct: you can read person.name
and person.age
just like you would with a struct. But, helpfully, we haven't had to define the struct ahead of time – this is something made to be thrown away. It also means you don't get to conform to protocols or write methods inside your tuples, but that's OK.
Tuples can be accessed using element names ("name" and "age" above), or using a position in the tuple, e.g. 0 and 1. You don't have to give your tuple elements names if you don't want to, but it's a good idea.
To give you a fully fledged tuple example, here's a function that splits a name like "Paul Hudson" in two, and returns a tuple containing the first name (Paul) and the last name (Hudson). Obviously this just a trivial example – it makes no attempt to cater for middle names, honorifics, or languages where family names come first!
func split(name: String) -> (firstName: String, lastName: String) {
let split = name.components(separatedBy: " ")
return (split[0], split[1])
}
let parts = split(name: "Paul Hudson")
parts.0
parts.1
parts.firstName
parts.lastName
As you can see, the return value from that function is (firstName: String, lastName: String)
, which is a tuple with named elements. Those elements then get accessed using split.0
, split.1
, split.firstName
and split.lastName
.
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 more!
Available from iOS 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.