Tracks
/
Swift
Swift
/
Syllabus
/
Multiple Return Values
Mu

Multiple Return Values in Swift

1 exercise

About Multiple Return Values

Multiple return values

Multiple values can be returned from Swift functions by creating and returning a tuple from the different values.

func reverseAndLength(_ str: String) -> (reverse: String, length: Int) {
  return (reverse: str.reverse, length: str.count)
}

reverseAndLength("Hello")
// => (reverse: "olleH", length: 5)

Omitting the return

func reverseAndLength(_ str: String) -> (reverse: String, length: Int) {
  (reverse: str.reverse, length: str.count)
}

In cases where the entire body of a function is a single expression, the return keyword may be omitted.

Note that this applies for all return types, not just multiple-value returns.

Edit via GitHub The link opens in a new window or tab

Learn Multiple Return Values