Leave a rating/review
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)")
}