For anybody who might find it useful. I found two other variations of the zip operator that could be used to resolve this challenge. One allows accepting two publishers as parameters instead of one and the other accepts a transform closure allowing to remove the map
operator from the solution.
Here’s how to use them:
example(of: "Original solution to the challenge") {
let phoneNumbersPublisher = ["123-4567", "555-1212", "555-1111", "123-6789"].publisher
let areaCodePublisher = ["410", "757", "800", "540"].publisher
let phoneExtensionPublisher = ["EXT 901", "EXT 523", "EXT 137", "EXT 100"].publisher
areaCodePublisher
.zip(phoneNumbersPublisher)
.map { $0 + "-" + $1 }
.zip(phoneExtensionPublisher)
.map { $0 + " " + $1 }
.sink {
print($0)
}
.store(in: &subscriptions)
}
example(of: "Example of zip with transform closure") {
let phoneNumbersPublisher = ["123-4567", "555-1212", "555-1111", "123-6789"].publisher
let areaCodePublisher = ["410", "757", "800", "540"].publisher
let phoneExtensionPublisher = ["EXT 901", "EXT 523", "EXT 137", "EXT 100"].publisher
phoneNumbersPublisher
.zip(areaCodePublisher) { [$1, $0].joined(separator: "-") }
.zip(phoneExtensionPublisher) { [$0, $1].joined(separator: " ") }
.sink {
print($0)
}
.store(in: &subscriptions)
}
example(of: "Solution with a single zip") {
let phoneNumbersPublisher = ["123-4567", "555-1212", "555-1111", "123-6789"].publisher
let areaCodePublisher = ["410", "757", "800", "540"].publisher
let phoneExtensionPublisher = ["EXT 901", "EXT 523", "EXT 137", "EXT 100"].publisher
areaCodePublisher
.zip(phoneNumbersPublisher, phoneExtensionPublisher)
.map { $0 + "-" + $1 + " " + $2 }
.sink {
print($0)
}
.store(in: &subscriptions)
}
1 Like