Updated for Xcode 14.2
With closures under your belt, it’s time to try a little coding challenge using them.
You’ve already met sorted()
, filter()
, map()
, so I’d like you to put them together in a chain – call one, then the other, then the other back to back without using temporary variables.
Your input is this:
let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]
Your job is to:
So, your output should be as follows:
7 is a lucky number
15 is a lucky number
21 is a lucky number
31 is a lucky number
33 is a lucky number
49 is a lucky number
If you need hints they are below, but honestly you should be able to tackle this one either from memory or by referencing recent chapters in this book.
Hacking with Swift+ subscribers can get a complete video solution for this checkpoint here: Solution to Checkpoint 5. If you don’t already subscribe, you can start a free trial today.
Still here? Okay, here are some hints:
filter()
, sorted()
, and map()
functions.sorted()
will do a string sort rather than an integer sort. That means 15 will come before 7, because Swift will compare the “1” in “15” against “7”.luckyNumbers.first { }.second { }
, obviously putting the real function calls in there.isMultiple(of:)
to remove even numbers.SPONSORED From March 20th to 26th, you can 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!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.