FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

Checkpoint 5

Paul Hudson    @twostraws   

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:

  1. Filter out any numbers that are even
  2. Sort the array in ascending order
  3. Map them to strings in the format “7 is a lucky number”
  4. Print the resulting array, one item per line

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:

  1. You need to use the filter(), sorted(), and map() functions.
  2. The order you run the functions matters – if you convert the array to a string first, 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”.
  3. To chain these functions, use luckyNumbers.first { }.second { }, obviously putting the real function calls in there.
  4. You should use isMultiple(of:) to remove even numbers.
Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

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

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.