Intermediate Combine

Apr 13 2021 · Swift 5.3, macOS 11.1, Xcode 12.2

Part 1: Intermediate Combine

04. Mapping Errors

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: 03. Managing Backpressure Next episode: 05. Retrying and Catching Errors

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.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

The differences between map and tryMap go 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. 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 a NameError enum that will provide errors when looking at passed-in names. Then make a just publisher and set the failure type to the NameError enum you defined above. Use the map operators to append " World" to the passed-in text from the publisher. 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. 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 named Error. 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 type throws yet. MapError can help us with this. Add a call to mapError right after the call to tryMap. This is casting the error to a name error, 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 code. Run this in the playground, and since tooShort is the error, the console shows you that hello is too short.