Home > AI > IOS > Combine >

replaceError(with:)

Example

struct MyError: Error {
    
}
let fail = Fail<String, MyError>(error: MyError())
let cancellable = fail
    .replaceError(with: "(replacement element)")
    .sink(
        receiveCompletion: { print ("good \($0)") },
        receiveValue: { print ("\($0)", terminator: " ") }
    )

Example 2: The error type of Publisher needs to be compatible with the error type of Subscriber such as assign and sink, whose error type is Never.

 let cancellable = URLSession.shared.dataTaskPublisher(for: url)
            .map{ UIImage(data: $0.data )}
            .replaceError(with: nil)
            .receive(on: DispatchQueue.main)
            .handleEvents(receiveOutput: {
                self.cache[self.urlString] = $0
            })
            .assign(to: \.image, on: self)

Leave a Reply