Skip to main content

optionals and nil coallescing

·76 words·1 min

Optionals and nil coallescing #

Up to the checkpoint https://www.hackingwithswift.com/100/swiftui/14

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Your challenge is this: write a function that
// accepts an optional array of integers and returns
// one randomly. If the array is missing or empty,
// return a random number in the range 1 through 100.

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

print(randomSelector(arr: [0,4,5,6]))
print(randomSelector(arr: nil))