UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

7      

+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!

4      

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.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.