實例方法
try
tryFilter(_:)
重新發布與提供的 error-throwing 閉包匹配的所有元素。
聲明
func tryFilter(_ isIncluded: @escaping (Self.Output) throws -> Bool) -> Publishers.TryFilter<Self>
返回值
重新發布滿足閉包的所有元素的發布者。
參數
isIncluded
一個閉包,它接受一個元素並返回一個布爾值,該值指示是重新發布該元素還是引發錯誤。
詳述
使用 Publisher/tryFilter(_:)
過濾在 error-throwing 閉包中評估的元素。如果 isIncluded
閉包引發錯誤,則發布者會因該錯誤而失敗。
在下麵的示例中,Publisher/tryFilter(_:)
檢查發布者提供的元素是否為零,並在終止發布者之前拋出 ZeroError
並拋出錯誤。否則,隻有當它是偶數時它才會重新發布元素:
struct ZeroError: Error {}
let numbers: [Int] = [1, 2, 3, 4, 0, 5]
cancellable = numbers.publisher
.tryFilter{
if $0 == 0 {
throw ZeroError()
} else {
return $0 % 2 == 0
}
}
.sink(
receiveCompletion: { print ("\($0)") },
receiveValue: { print ("\($0)", terminator: " ") }
)
// Prints: "2 4 failure(DivisionByZeroError())".
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher tryFirst(where:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher tryReduce(_:_:)用法及代碼示例
- 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 tryFilter(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。