Toshi
Toshi

Reputation: 6342

Tuples in Swift

There is a new type added in Swift which is Tuples. I only know the values within a tuple can be of any type and do not have to be of the same type as each other. But other than that, Is there anything that array/dictionary can't do, but tuples can, and vice versa?

Upvotes: 1

Views: 2591

Answers (2)

Steve Rosenberg
Steve Rosenberg

Reputation: 19524

Ah, just yesterday I gave an answer using a function which returns a tuple. To output two values of different types. Someone wanted to use a switch statement to match a dog name and age:

func dogMatch(age: Int, name: String) -> (Match: String, Value: Int)  {

    switch (age, name) {
    case(age, "wooff"):
        println("My dog Fido is \(age) years old")
        return ("Match", 1)
    case (3, "Fido"):
        return ("Match", 10)
    default:
        return ("No Match", 0)
    }
}

dogMatch(3, "Fido").Match
dogMatch(3, "Fido").Value

Notice that the tuple contains values of different types.

Upvotes: 3

Logan
Logan

Reputation: 53112

One thing that comes to mind is named variables in a tuple. In some cases, this is preferable to keys or indexes:

let newTuple = (variableOne: 20, variableTwo: "Hi There")
newTuple.variableOne
newTuple.variableTwo

You can use typealias to apply this further:

typealias namedTuple = (variableOne: Int, variableTwo: String)

let newTuple: namedTuple = (20, "Hi There")
newTuple.variableOne
newTuple.variableTwo

You can also be more explicit about return types in functions:

func controlledReturnType() -> (Int, String) {
    return (1, "Yup")
}

Upvotes: 1

Related Questions