The differences between map and tryMap goes beyond the fact that tryMap allows throwing errors. map carries over any existing failure types, but tryMap does not - it instead erases the error to a plain Swift Error type. So what do you do if you want to keep some knowledge of that error type around? That’s where mapError comes into play.
Add an example block, and within that define an NameError enum will provide errors when looking at passed in names.
example(of: "map vs tryMap") {
// 1
enum NameError: Error {
case tooShort(String)
case unknown
}
Then make a Just publisher, and set the failure type to the NameError enum you defined above.
// 2
Just("Hello")
.setFailureType(to: NameError.self) // 3
Use the map operatrs to append “ World” to the passed in text from the publisher
.map { $0 + " World!" } // 4
Attach a sink, and in the completion block add a switch that prints different strings to the console based on if the publisher finished, or if it received an error.
.sink(
receiveCompletion: { completion in
// 5
switch completion {
case .finished:
print("Done!")
case .failure(.tooShort(let name)):
print("\(name) is too short!")
case .failure(.unknown):
print("An unknown name error occurred")
}
},
receiveValue: { print("Got value \($0)") }
)
.store(in: &subscriptions)
}
If you run the playground now, you’ll see that it got the value “Hello World” as well as the completion event. If you option-click on the term completion in the code, you’ll see the completion’s failure type is NameError. Try changing the map to tryMap and repeating that process.
When you option-click this time, you’ll see that the failure type is now a simple Error and that your specific type has been erased! This is because Swift doesn’t support typed throws yet.
mapError can help us with this. Add a call to mapError right after the call to tryMap
.mapError { $0 as? NameError ?? .unknown }
This is casting the error to a NameError and if that fails, falls back to .unknown. Run the playground and you’ll find it works as expected. One way to make sure that mapError is working is to force an error. Replace the entire tryMap call with the following:
.tryMap { throw NameError.tooShort($0) }
Run this in the playground, and since tooShort is the error, the console shows you that “Hello” is too short.