Instance Methodswift 6.0.3Swift

mapError(_:)

Returns a new result, mapping any failure value using the given transformation.

consuming func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> Result<Success, NewFailure> where NewFailure : Error

Parameters

transform

A closure that takes the failure value of the instance.

Returns

A Result instance with the result of evaluating transform as the new failure value if this instance represents a failure.

Use this method when you need to transform the value of a Result instance when it represents a failure. The following example transforms the error value of a result by wrapping it in a custom Error type:

struct DatedError: Error {
    var error: Error
    var date: Date

    init(_ error: Error) {
        self.error = error
        self.date = Date()
    }
}

let result: Result<Int, Error> = // ...
// result == .failure(<error value>)
let resultWithDatedError = result.mapError { DatedError($0) }
// result == .failure(DatedError(error: <error value>, date: <date>))