Updated for Xcode 13.3
Now that you understand a little about optionals, it’s time to pause for a few minutes and try a small coding challenge so you can see how much you’ve remembered.
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.
If that sounds easy, it’s because I haven’t explained the catch yet: I want you to write your function in a single line of code. No, that doesn’t mean you should just write lots of code then remove all the line breaks – you should be able to write this whole thing in one line of code.
I’ll provide some hints in a moment, but first I recommend you go ahead and try it yourself.
Hacking with Swift+ subscribers can get a complete video solution for this checkpoint here: Solution to Checkpoint 9. If you don’t already subscribe, you can start a free trial today.
Still here? Okay, here are some hints:
[Int]?
– an array of integers that might be there, or might be nil
.Int
.randomElement()
on the optional array, which will in turn return another optional.SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.