Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Tuples as Function Return Types in Swift
Written by Team Kodeco

In Swift, you can use tuples as the return type of a function. This allows a function to return multiple values at once.

Here’s an example of how to create a function that returns a tuple:

func getTuple() -> (Int, String) {
  return (1, "apple")
}

let tuple = getTuple()
print(tuple.0)  // 1
print(tuple.1)  // "apple"

You can also use named tuples as the return type of a function:

func getNamedTuple() -> (number: Int, fruit: String) {
  return (number: 1, fruit: "apple")
}

let namedTuple = getNamedTuple()
print(namedTuple.number)  // 1
print(namedTuple.fruit)  // "apple"
© 2024 Kodeco Inc.