Swift Introduction | Functions | Multiple Return Values and Tuples

Swift functions have several interesting features. One important feature is the ability to return multiple values.

The key is not a special feature of functions themselves, but Swift’s tuple values.

A tuple groups multiple values together. Create one with parentheses.

(name:value, name:value, ...)

Retrieve values from a tuple by specifying their names.

var person = (name:"Taro", age:35)
person.name
person.age

This code assigns a tuple containing name and age to the person variable. Retrieve its values as person.name and person.age.

Using a Tuple as a Return Value

Once you understand tuples, a function that returns multiple values is easy to create.

func tax(price:Int) -> (kakaku:Int, zei:Int) {
    let zei:Int = Int(Double(price) * 0.08)
    let kakaku:Int = price - zei
    return (kakaku:kakaku, zei:zei)
}

var res = tax(10000)
res.kakaku
res.zei

Specify the return value as follows.

-> (kakaku:Int, zei:Int)

This declaration specifies a tuple containing kakaku and zei as the return value. After calling the function, retrieve the values from the variable that receives the result.