Leave a rating/review
You’ve learned all about Prepending and Appending operators - so now it’s time for a challenge. Back in the day, phone numbers used to be a lot easier to remember! 7 digits (in the United States, at least) was all you needed to remember to call your best friend. Now you need area codes, and if you’re calling a business, you’ll probably need to know a person’s extension, and if the number was long distance, you’d need to prepend a “1” in front of it. So for this challenge:
In the starter project, you’ll find an array with one 7 digit phone number, represented as a string. You’ll also find 2 values: an area code, 410 (that goes before the number), and an extension, 901, that goes after the string “EXT”, which follows the phone number.
To complete this challenge, take the 7 digit number emitted by the publisher and turn it into a phone number of the form 1-410- the phone number followed by the string EXT followed by the number 901 using what you’ve learned about prepending and appending operators. Pause the video, try to come up with a solution, and when you’re ready, resume the video. Note that there may be multiple ways to accomplish this challenge!
Here’s a hint - to print out your output in the format above, use the joined() method to combine the different elements of the string together! Good luck!
Were you able to avoid the dreaded “This number cannot be completed as dialed” error message from the phone company? Let’s take a look at the solution:
example(of: "Making Phone Numbers") {
let phoneNumbersPublisher = ["123-4567"].publisher
let areaCode = "410"
let phoneExtension = "901"
phoneNumbersPublisher
.prepend("1-", areaCode, "-")
.append(" EXT ")
.append(phoneExtension)
.collect()
.sink(receiveValue:
{
print($0.joined())
})
.store(in: &subscriptions)
}
Did you get this solution, or something similar using the various types of prepend and append operators? If so, congrats!
But what if you had a series of extensions and areas codes to deal with? That involves some more advanced combining operators, which happens to be the topic of the next episode in the course. See you then!