Welcome to the first article of many in our new series The Swift Interviewer!
This series is intended for you to step into the shoes of the interviewee with a series of questions that will be asked throughout this article. Today, we'll be talking all about tuples. There's no time to waste, so let's get right into it!
A tuple is a comma-separated list of zero or more types, in which all of those types are enclosed within parenthesis.
var firstName = "John"
var lastName = "Doe"
var person = (firstName: "John", lastName: "Doe")
AnswerA tuple that doesn't have any named properties may look something like this:
var person = ("John", "Doe")
If a tuple doesn't have any named values, you can access a specific value at the n-1 index, where n is the location in the tuple. For example:
person.0 // John
person.1 // Doe
AnswerYes, you can nest tuples. It provides an additional level of clarity in a lot of cases when you want to group related values. In our example above, we can create a nested tuple to hold the values of firstName and lastName.
var person = (name: (first: "John", last: "Doe"), address: "123 Candy Lane")
person.name.first // John
person.name.last // Doe
person.address // 123 Candy Lane