Tuples Example Swift 4 - Return Multiple values from Function - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

5 Nov 2017

Tuples Example Swift 4 - Return Multiple values from Function

Tuples looks like same as dictionary which holds specific type of data.

Tuples are mainly used for returning multiple value from a function.

Tuples Syntax:

we can create in two ways as follow:

// first way
let person = ("John", "Sam", "Nina")
print(person.0, person.1, person.2) // output looks like : John Sam Nina

// second way most preffered
let p = (name: "Steve", gender: "Male", age: 25)
print(p.name, p.gender, p.age) // output looks like: Steve Male 25

Usage :

Here we will show how to use tuples with an example:

func getTwoHighestNumbersFromList(numbers: [Int]) -> (Int?, Int?) {
    
    if numbers.isEmpty { // optional checking
        return (nil, nil)
    }else if numbers.count == 1 {
        return (numbers[0], nil)
    }
    
    let sortedList = numbers.sorted { (x, y) -> Bool in
        return x > y
    }
    
    return (sortedList[0], sortedList[1]) // returning tuples
}

let highestNumbers = getTwoHighestNumbersFromList(numbers: [1234, 34, 4, 89, 21, 435, 23])
highestNumbers.0
highestNumbers.1

As you can see, the return value from that function is (Int, Int), which is a tuple. Those elements then get accessed using highestNumbers.0, highestNumbers.1.

No comments:

Post a Comment

Post Top Ad