Start learning free

LESSON 274 OF 678 · TUPLES, SORTING & BUILT-INS

Min, Max and Sum in Swift

Lesson

TL ; DR:

arr.min() and arr.max() give the smallest and the largest value of an array, as optionals.

arr.reduce(0, +) adds all the values up.


let prices = [4, 9, 2, 7]

print(prices.min()!)          // 2
print(prices.max()!)          // 9
print(prices.reduce(0, +))    // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. Swift arrays have ready-made methods for them.

  • arr.min() gives the smallest value of the array arr.
  • arr.max() gives the largest value.
  • arr.reduce(0, +) adds all the values up.

min() and max() return an optional. An empty array has no smallest value, so they give nil there. The ! takes the value out, as in Optionals & Unwrapping.

Swift has no sum(). reduce(0, +) starts at 0 and adds each value with +, from left to right.

The global max(a, b) from Maximum Number In Array compares two values. arr.max() looks at a whole array.

Watch out for an empty array. There, arr.min()! crashes, because the ! finds nil. When the array may be empty, write arr.min() ?? 0 for a fallback. reduce(0, +) of an empty array is 0.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check