Returning a Tuple in Swift

Level 3311 keystrokes

A function returns the minimum and maximum of an array as an optional named tuple (nil for an empty array); the caller unwraps it with if let and prints "Min: 1, Max: 5".

Swift code

// Returns a named tuple (min:, max:); the ? makes the whole tuple optional
1func minMax(_ array: [Int]) -> (min: Int, max: Int)? {
// For an empty array first is nil, so the function returns nil
2 guard let first = array.first else { return nil }
// Two variables in one declaration, both starting at the first element
3 var min = first, max = first
// Compare every element and update min and max when needed
4 for n in array {
5 if n < min { min = n }
6 if n > max { max = n }
7 }
// The values fill the tuple labels min and max in order
8 return (min, max)
9}
10
// if let unwraps the optional tuple; the block is skipped if it is nil
11if let result = minMax([3, 1, 4, 1, 5]) {
// Elements are read by their labels: Min: 1, Max: 5
12 print("Min: \(result.min), Max: \(result.max)")
13}

Output

Min: 1, Max: 5
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • ,× 8
  • (× 7
  • )× 7
  • {× 6
  • }× 6
  • =× 6
  • :× 5
  • .× 3
  • "× 2
  • [× 2

More Swift examples at level 3

← Swift typing practice