實例方法
map
mapError(_:)
將來自上遊發布者的任何失敗轉換為新錯誤。
聲明
func mapError<E>(_ transform: @escaping (Self.Failure) -> E) -> Publishers.MapError<Self, E> where E : Error
返回值
使用 transform
閉包產生的新錯誤替換任何上遊故障的發布者。
參數
transform
一個閉包,它將上遊失敗作為參數並返回一個新的錯誤以供發布者終止。
詳述
當您需要將一種錯誤類型替換為另一種錯誤類型時,或者下遊運算符需要其輸入的錯誤類型匹配時,請使用 Publisher/mapError(_:)
運算符。
以下示例使用 Publisher/tryMap(_:)
運算符將 1
除以序列發布者生成的每個元素。當發布者生成 0
時,Publisher/tryMap(_:)
失敗並顯示 DivisionByZeroError
。 Publisher/mapError(_:)
運算符將其轉換為 MyGenericError
。
struct DivisionByZeroError: Error {}
struct MyGenericError: Error { var wrappedError: Error }
func myDivide(_ dividend: Double, _ divisor: Double) throws -> Double {
guard divisor != 0 else { throw DivisionByZeroError() }
return dividend / divisor
}
let divisors: [Double] = [5, 4, 3, 2, 1, 0]
divisors.publisher
.tryMap { try myDivide(1, $0) }
.mapError { MyGenericError(wrappedError: $0) }
.sink(
receiveCompletion: { print ("completion: \($0)") ,
receiveValue: { print ("value: \($0)", terminator: " ") }
)
// Prints: "0.2 0.25 0.3333333333333333 0.5 1.0 completion: failure(MyGenericError(wrappedError: DivisionByZeroError()))"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
- Swift Result.Publisher map(_:_:)用法及代碼示例
- Swift Result.Publisher max()用法及代碼示例
- Swift Result.Publisher makeConnectable()用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher min()用法及代碼示例
- Swift Result.Publisher multicast(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher multicast(subject:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:)用法及代碼示例
- Swift Result.Publisher measureInterval(using:options:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher print(_:to:)用法及代碼示例
- Swift Result.Publisher sink(receiveValue:)用法及代碼示例
- Swift Result.Publisher eraseToAnyPublisher()用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher mapError(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。