Generic Instance Method

mapError(_:)

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

Declaration

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

Parameters

transform

A closure that takes the failure value of the instance.

Return Value

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

Discussion

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({ e in DatedError(e) })
// result == .failure(DatedError(error: <error value>, date: <date>))

See Also

Transforming a Result

func map<NewSuccess>((Success) -> NewSuccess) -> Result<NewSuccess, Failure>

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

func flatMap<NewSuccess>((Success) -> Result<NewSuccess, Failure>) -> Result<NewSuccess, Failure>

Returns a new result, mapping any success value using the given transformation and unwrapping the produced result.

func flatMapError<NewFailure>((Failure) -> Result<Success, NewFailure>) -> Result<Success, NewFailure>

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