實例方法
compact
compactMap(_:)
使用每個接收到的元素調用閉包並發布任何返回的具有值的可選。
聲明
func compactMap<T>(_ transform: @escaping (Self.Output) -> T?) -> Publishers.CompactMap<Self, T>
返回值
調用提供的閉包的任何非 nil
可選結果。
參數
transform
一個接收一個值並返回一個可選值的閉包。
詳述
Combine 的 Publisher/compactMap(_:)
運算符執行類似於 Swift 標準庫中的
的函數:Combine 中的 compactMap(_:)
Publisher/compactMap(_:)
運算符刪除發布者流中的 nil
元素,並將非 nil
元素重新發布給下遊訂閱者。
下麵的示例使用一係列數字作為基於集合的發布者的來源。 Publisher/compactMap(_:)
運算符使用來自 numbers
發布者的每個元素,嘗試使用元素作為鍵來訪問字典。如果示例的字典返回 nil
,由於鍵不存在,Publisher/compactMap(_:)
會過濾掉 nil
(缺失)元素。
let numbers = (0...5)
let romanNumeralDict: [Int : String] =
[1: "I", 2: "II", 3: "III", 5: "V"]
cancellable = numbers.publisher
.compactMap { romanNumeralDict[$0] }
.sink { print("\($0)", terminator: " ") }
// Prints: "I II III V"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Optional.Publisher combineLatest(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher combineLatest(_:_:_:)用法及代碼示例
- Swift Optional.Publisher combineLatest(_:_:)用法及代碼示例
- Swift Optional.Publisher combineLatest(_:)用法及代碼示例
- Swift Optional.Publisher collect(_:)用法及代碼示例
- Swift Optional.Publisher contains(_:)用法及代碼示例
- Swift Optional.Publisher collect(_:options:)用法及代碼示例
- Swift Optional.Publisher catch(_:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代碼示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代碼示例
- Swift Optional.Publisher mapError(_:)用法及代碼示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher sink(receiveValue:)用法及代碼示例
- Swift Optional.Publisher scan(_:_:)用法及代碼示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Optional.Publisher assertNoFailure(_:file:line:)用法及代碼示例
- Swift Optional.Publisher share()用法及代碼示例
- Swift Optional.Publisher merge(with:_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:)用法及代碼示例
- Swift Optional.Publisher assign(to:on:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher output(in:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional.Publisher compactMap(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。