Tuples – holding multiple values in a variable

We saw that we can declare variables or constants to hold values that we could use in our code instead of hard-coding them. We could also return values from functions however in most languages you can only return a single value. Mainly this return value would be more like a Boolean value that indicated if the function was successful or not as most of the functions would alter the parameters passed to the function.
As programming languages developed the need for passing more parameters increased and instead of a single parameter, developers wanted to pass a structure that encompassed multiple values.

What is a tuple. A tuple is a compound type that can hold multiple values and can also be used with functions. You could also use structs instead but the advantage of a tuple is that they are temporary group of related values. Apple recommends that if you need to persist the values returned by a tuple or are complex, then you should consider other alternatives like structures or classes.

How do you create a tuple? The key in the definition of a tuple – temporary group of related values.

var myTuple = (8,"iOS", 2015)

This creates a tuple that is referenced via the variable called myTuple. However that references the entire tuple, how would you access the individual members of the tuple? Swift automatically assigns a numeric index to the values, the first value is referenced with a 0, the second with a 1 and so on. Since these are members of the tuple, they are referenced as properties of the tuple

var myTuple = (8, "iOS", 2015)
println("\(myTuple.1)\(myTuple.0) available in \(myTuple.2)")

It is a bit inconvenient to access tuples using this schema as you would never know what you are accessing after all .0 simply means the first member. The good bit is that you can actually access the members of the tuple as named values, like you would with a structure or properties of a class. Consider the code

var namedTuple = (version:6, software:"Xcode")
println("\(namedTuple.version) is the latest version of \(namedTuple.software)")

You could also define the tuple without assigning it any values and use it like a structure, which could be like

var tupleStructure:(version:Int, software:String)

then assign/alter the values as required later on in the code as

tupleStructure.version = 10
tupleStructure.software = "Windows"

Tuples can also be used as return values from functions.
consider the code

func getBookIssued(bookCode:String) -> (title:String, dueOn:String, bookCode:String)

This indicates that the function will take a bookCode which is a string value and will return the title of the book and the date when it is due including the bookCode. The code that makes up the body of this function could look something like

func getBookIssued(bookCode:String) -> (title:String, dueOn:String, bookCode:String){
    // Query the details of the book based on the code passed
    // and say that the result in in the class variable called book
    // and the variable dueDate is two weeks from today
    
    return (title:book.title, dueOn:dueDate, bookCode:bookCode)
}

Another example could be in the case of a highscore table, where you might want to save the name of the player, the score and the level reached. You could get a tuple with these values as

var highscoreEntry = (name:String, score:Double, level:Int)

and this could be used in code to display the top 10 scores as

for i in 1...10 {
 var entry = getHighScoreAtIndex(i)
 println("\(i). \(entry.name) scored \(entry.score) and completed level \(entry.level)")
}

Tuples like variables can be optionals. Which means that they can also be nil. For a detailed article on optionals, please look out for a later article coming soon.

In our earlier example, what happens if the bookCode passed to the function did not have any details because the book code did not exist. It would be easier to return a nil, but it is not possible to simply return nil as a substitute for a variable type. Our function could now look like

function getBookIssued(bookCode:String) -> (title:String, dueOn:String, bookCode:String)? {
    //Query the details of the book based on the code passed
    // into the class variable called book
    //
    //
    if let book = getBookFromCode(bookCode) {
        return(title:book.title, dueOn:dueDate, bookCode:bookCode)
    } else {
        // There are no details and hence return nil
        return nil
    }
}

Tuples can be used in all scenarios where other variables can be used, like when used a ‘switch case’ or conditionals.

Views All Time
Views All Time
4061
Views Today
Views Today
1
Posted in Basics, Tutorial and tagged , , , .