WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Checkpoint 9 - Viable solutions?

Forums > 100 Days of SwiftUI

Here I am at checkpoint 9 and I came up with two ways to solve it. The actual func way:

func mindBlown(_ input: [Int]?) -> Int { return input?.randomElement() ?? Int.random(in: 1...100) }
print(mindBlown(nil))       // This prints a random number.
print(mindBlown([0, 1]))    // This prints 0 or 1.

The neat way, although this one does require making the array first:

let array: [Int]? = nil
let mindBlown = array?.randomElement() ?? Int.random(in: 1...100)
print(mindBlown) // Depending on whether the array is nil or not,
                 // prints a random number from the array or anything from 1 to 100.

Did I miss anything obvious? Does the neat way qualify as a solution?


+1 for function name.

Look at all the concepts you've included! Optional variables. Nil coalescing operators. Type functions. Dual parameters. Array processing. Parameter name hiding.

All in one line of code.

Mind blown!


Thanks. :D That's how I felt when it worked. A lot of trial and error was involved and these concepts are certainly something that takes practice.

And thank you for replying to my questions so far. You have been very helpful an supportive and I truly appreciate it.


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.