实例方法
try
tryFirst(where:)
发布流的第一个元素以满足抛出谓词闭包,然后正常结束。
声明
func tryFirst(where predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryFirstWhere<Self>
返回值
仅发布满足谓词的流的第一个元素的发布者。
参数
predicate
一个闭包,它接受一个元素作为参数并返回一个布尔值,指示是否发布该元素。
详述
当您只需要重新发布满足您指定的error-throwing 闭包的流的第一个元素时,请使用Publisher/tryFirst(where:)
。发布者忽略第一个元素之后的所有元素。如果这个发布者没有收到任何元素,它会在没有发布的情况下完成。如果谓词闭包抛出错误,则发布者失败。
在下面的示例中,范围发布者发出范围中的第一个元素,然后正常结束:
let numberRange: ClosedRange<Int> = (-1...50)
numberRange.publisher
.tryFirst {
guard $0 < 99 else {throw RangeError()}
return true
}
.sink(
receiveCompletion: { print ("completion: \($0)", terminator: " ") },
receiveValue: { print ("\($0)", terminator: " ") }
)
// Prints: "-1 completion: finished"
// If instead the number range were ClosedRange<Int> = (100...200), the tryFirst operator would terminate publishing with a RangeError.
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift Optional.Publisher tryFilter(_:)用法及代码示例
- 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 tryFirst(where:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。