Reactive Programming in iOS with Combine

Feb 4 2021 · Swift 5.3, macOS 11.0, Xcode 12.2

Part 2: Transforming & Filtering Operators

09. Challenge: Create a Phone Number Lookup

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 08. More Transforming Operators Next episode: 10. Filtering Operators

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 09. Challenge: Create a Phone Number Lookup

OK, that was a lot of information about Transforming Operators, so I’ve got a challenge for you before moving on. For this challenge, you need to create a publisher that does 2 things: receive a string of ten numbers or letters, and look up those numbers in a contacts data structure.

The starter playground in the challenge folder for this part of the course has a contacts dictionary and three functions to help you out.

You’ll need to create a subscriber to the provided input publisher, and use the functions and transformating operators to do the following. Convert the input to numbers. Make sure you handle nil cases where the string can’t be converted to numbers! If you get a nil from the conversion, replace it with 0. Collect 10 values at a time and format the collected strings to match the 3 digit area code and seven digit phone number format used in the United States. “Dial” the input received from the previous operator using the dial function

Don’t forget, closures and functions can be passed into operators, as long as their function signatures match up. Pause the video, try the challenge, and then come back to see the solution!

Did you get the expected results? Let’s break down the steps we went over earlier with some actual code. First, you need to convert the input using the convert method - which can be done with the map operator

input
  .map(convert)

Then, replace any nils with 0s

.replaceNil(with: 0)

The collection function read in and processed one character at a time, so we need to collect 10 of them together to get a phone number. We can do that with the collect operator, and once that is done, we can map those results to a nicer looking format with the format function.

.collect(10)
.map(format)

Finally, we can walk through each phone number and “dial” it using the dial function passed into the map operator, and pass that end result into a sink subscriber that prints out the result.

.map(dial)
.sink(receiveValue: { print($0) })
"0!1234567".forEach {
input.send(String($0))
}
  
"4085554321".forEach {
input.send(String($0))
}
  
"A1BJKLDGEH".forEach {
input.send("\($0)")
}