NEW: Learn to build the incredible iOS 15 Weather app today! >>

Checkpoint 5

Paul Hudson    @twostraws   

Updated for Xcode 13.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:

  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 Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for iOS devs who want to become complete Senior iOS Developers.

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!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.