實例方法
try
tryCompactMap(_:)
使用每個接收到的元素調用 error-throwing 閉包,並發布任何返回的具有值的可選。
聲明
func tryCompactMap<T>(_ transform: @escaping (Self.Output) throws -> T?) -> Publishers.TryCompactMap<Self, T>
返回值
調用提供的閉包的任何非 nil
可選結果。
參數
transform
error-throwing 閉包,接收一個值並返回一個可選值。
詳述
使用 Publisher/tryCompactMap(_:)
根據您提供的 error-throwing 閉包從發布者的流中刪除 nil
元素。如果閉包拋出錯誤,發布者取消上遊發布者並將拋出的錯誤作為 Publisher/Failure
發送給下遊訂閱者。
以下示例使用數字數組作為基於集合的發布者的源。 Publisher/tryCompactMap(_:)
運算符使用來自發布者的每個整數,並使用字典將數字從其阿拉伯數字轉換為羅馬數字,作為可選的
。String
如果 Publisher/tryCompactMap(_:)
調用的閉包無法查找羅馬數字,則返回可選字符串 (unknown)
。
如果 Publisher/tryCompactMap(_:)
調用的閉包確定輸入是 0
,則會引發錯誤。 Publisher/tryCompactMap(_:)
運算符捕獲此錯誤並停止發布,發送包裝錯誤的 Subscribers/Completion/failure(_:)
。
struct ParseError: Error {}
func romanNumeral(from: Int) throws -> String? {
let romanNumeralDict: [Int : String] =
[1: "I", 2: "II", 3: "III", 4: "IV", 5: "V"]
guard from != 0 else { throw ParseError() }
return romanNumeralDict[from]
}
let numbers = [6, 5, 4, 3, 2, 1, 0]
cancellable = numbers.publisher
.tryCompactMap { try romanNumeral(from: $0) }
.sink(
receiveCompletion: { print ("\($0)") },
receiveValue: { print ("\($0)", terminator: " ") }
)
// Prints: "(Unknown) V IV III II I failure(ParseError())"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Result.Publisher tryFilter(_:)用法及代碼示例
- Swift Result.Publisher tryFirst(where:)用法及代碼示例
- Swift Result.Publisher tryPrefix(while:)用法及代碼示例
- Swift Result.Publisher tryScan(_:_:)用法及代碼示例
- Swift Result.Publisher tryMap(_:)用法及代碼示例
- Swift Result.Publisher tryDrop(while:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- 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:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher tryCompactMap(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。