Multiple Return Values in Swift

Swift supports multiple return values, which is a feature often used to return both a result and an error value from a function.

import Foundation

// The `(Int, Int)` in this function signature shows that
// the function returns 2 `Int`s.
func vals() -> (Int, Int) {
    return (3, 7)
}

func main() {
    // Here we use the 2 different return values from the
    // call with multiple assignment.
    let (a, b) = vals()
    print(a)
    print(b)

    // If you only want a subset of the returned values,
    // use the underscore `_` as a placeholder.
    let (_, c) = vals()
    print(c)
}

main()

To run the program, save it as multiple_return_values.swift and use the Swift compiler:

$ swift multiple_return_values.swift
3
7
7

Swift’s tuple return type allows functions to return multiple values, which is similar to the feature in the original example. The syntax is slightly different, with Swift using a tuple (Int, Int) instead of separate comma-separated types.

In Swift, we use let for constant declarations instead of :=. The multiple assignment syntax is similar, using a tuple on the left side of the assignment.

For ignoring values, Swift uses an underscore _ as a placeholder, which is functionally equivalent to the blank identifier in the original example.

The print function in Swift is equivalent to fmt.Println for simple output.

Swift doesn’t require an explicit main function as the entry point of the program, but we’ve included one here to maintain the structure of the original example. In a real Swift program, you could omit the main function and just write the code at the top level of the file.

Accepting a variable number of arguments is also a feature in Swift, which we’ll explore in a future example.