Ad space (banner)
๐ŸฆSwift Lessons
Lesson 47 / 68

Functions That Return Multiple Values (Tuples)

In this lesson you will learn how to return several values from one function in Swift using tuples, so you are not limited to a single return value. This is for anyone searching for "Swift tuple multiple return values".

A Swift function can return several values at once by returning a tuple such as (min: Int, max: Int). Picture handing over one box containing two cards, a name and a score.

The sample code declares the return type as func minMax(_ nums: [Int]) -> (min: Int, max: Int) and returns both with return (nums.min()!, nums.max()!). The caller reaches each value by name, as result.min and result.max.

A common stumbling block for beginners is not knowing how useful labelled tuples are. Labelling them lets you read values out under meaningful names such as result.min, which makes the code far easier to follow.

In real-world development, being able to do casually with a tuple what other languages need an array or an object for is one of Swift's conveniences.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)