实例方法
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 Optional.Publisher tryFirst(where:)用法及代码示例
- Swift Optional.Publisher tryDrop(while:)用法及代码示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代码示例
- Swift Optional.Publisher tryReduce(_:_:)用法及代码示例
- Swift Optional.Publisher tryPrefix(while:)用法及代码示例
- Swift Optional.Publisher tryScan(_:_:)用法及代码示例
- Swift Optional.Publisher tryMax(by:)用法及代码示例
- Swift Optional.Publisher tryContains(where:)用法及代码示例
- Swift Optional.Publisher tryCompactMap(_:)用法及代码示例
- Swift Optional.Publisher tryRemoveDuplicates(by:)用法及代码示例
- Swift Optional.Publisher tryMap(_:)用法及代码示例
- Swift Optional.Publisher tryLast(where:)用法及代码示例
- Swift Optional.Publisher tryMin(by:)用法及代码示例
- Swift Optional.Publisher tryCatch(_:)用法及代码示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代码示例
- Swift Optional.Publisher timeout(_:scheduler:options:customError:)用法及代码示例
- Swift Optional.Publisher reduce(_:_:)用法及代码示例
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代码示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代码示例
- Swift Optional.Publisher mapError(_:)用法及代码示例
- Swift Optional.Publisher catch(_:)用法及代码示例
- Swift Optional.Publisher zip(_:_:_:)用法及代码示例
- Swift Optional.Publisher sink(receiveValue:)用法及代码示例
- Swift Optional.Publisher scan(_:_:)用法及代码示例
- Swift Optional.Publisher assertNoFailure(_:file:line:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Optional.Publisher tryFilter(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。