Multiple Returns

Functions can return more than one value. To do this, Swift uses the tuple data type, which you learned about in Chapter 5. Recall that a tuple is an ordered list of related values. To better understand how to use tuples, you are going to make a function that takes an array of integers and sorts them into arrays for even and odd integers.

Listing 12.10  Sorting evens and odds

...
func sortEvenOdd(numbers: [Int]) -> (evens: [Int], odds: [Int]) {
    var evens = [Int]()
    var odds = [Int]()
    for number in numbers {
        if number % 2 == 0 {
            evens.append(number)
        } else {
            odds.append(number)
        }
    }
    return (evens, odds)
}

Here, you first declare a function called sortEvenOdd(_:). You specify this function to take an array of ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.