實例方法
filter(_:)
重新發布與提供的閉包匹配的所有元素。
聲明
func filter(_ isIncluded: @escaping (Self.Output) -> Bool) -> Publishers.Filter<Self>
返回值
重新發布滿足閉包的所有元素的發布者。
參數
isIncluded
一個閉包,它接受一個元素並返回一個布爾值,指示是否重新發布該元素。
詳述
Combine 的 Publisher/filter(_:)
運算符執行類似於 Swift 標準庫中的
的操作:它使用閉包來測試每個元素,以確定是否將元素重新發布給下遊訂閱者。filter(_:)
以下示例使用接收 Int
的過濾器操作,並且僅在其為偶數時才重新發布一個值。
let numbers: [Int] = [1, 2, 3, 4, 5]
cancellable = numbers.publisher
.filter { $0 % 2 == 0 }
.sink { print("\($0)", terminator: " ") }
// Prints: "2 4"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- 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 output(at:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
- Swift Result.Publisher append(_:)用法及代碼示例
- Swift Result.Publisher breakpointOnError()用法及代碼示例
- Swift Result.Publisher handleEvents(receiveSubscription:receiveOutput:receiveCompletion:receiveCancel:receiveRequest:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher filter(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。