O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 sortedEvenOddNumbers(_ 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 sortedEvenOddNumbers(_:). You specify this function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required