an artist's impression of a black hole in the sky

100 Days of SwiftUI – Day 14

Our last day of Swift fundamentals is about optionals – as I understand it, the ability for a variable to either have a value or not. We learn why we need them and how to use them.

In Day 14 we learn that there’s three ways to ‘unwrap’ an optional in order to discover whether there’s a value within or if it’s nil.

  1. Using if let: we use this to run some code if the variable does contain a value.
  2. Using guard let: this allows us to run code if the variable doesn’t contain a value (i.e. is nil).
  3. Nil coalescing (??): here we check if there’s a value and if there is, we use it, if there isn’t, we provide a sensible default to use instead.

We also cover using try? which allows us to call a throwing function (i.e. one which might return errors) and return either the function’s value or nil if it failed, without returning the actual error.

Checkpoint 9

Our checkpoint challenge is to write a one-line function that accepts an optional array and either:

  • Returns a random element of the array if it is passed one; or
  • Returns any random value between 1 and 100 instead.

This isn’t too hard, the function needs to take in an optional array, return an Int and, within, attempt to unwrap the optional array and do a thing or do something else if nil is passed instead.

func randomNumber(in array: [Int]?) -> Int { array?.randomElement() ?? Int.random(in: 1...100) }

// Test input
let numbers: [Int]? = nil
print(randomNumber(in: numbers))

let numbers2: [Int]? = [2, 3, 4]
print(randomNumber(in: numbers2))

In the above, the first print statement always gives us a random Int between 1 and 100 and the second always gives us a random element from the given array of numbers.