实例方法
try
tryDrop(while:)
忽略上游发布者的元素,直到 error-throwing 闭包返回 false,然后重新发布所有剩余元素。
声明
func tryDrop(while predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryDropWhile<Self>
返回值
一个发布者跳过元素直到提供的闭包返回 false
,然后重新发布所有剩余的元素。如果谓词闭包抛出,发布者将失败并出现错误。
参数
predicate
一个闭包,它接受一个元素作为参数并返回一个布尔值,指示是否从发布者的输出中删除该元素。
详述
使用Publisher/tryDrop(while:)
省略上游元素,直到您提供的error-throwing 闭包返回false,之后发布流中的剩余项目。如果闭包抛出,则不会发出任何元素,并且发布者会因错误而失败。
在下面的示例中,元素被忽略,直到在流中遇到 -1
并且闭包返回 false
。然后发布者重新发布剩余的元素并正常完成。相反,如果遇到闭包中的 guard
值,则闭包将抛出,并且发布者将失败并出现错误。
struct RangeError: Error {}
var numbers = [1, 2, 3, 4, 5, 6, -1, 7, 8, 9, 10]
let range: CountableClosedRange<Int> = (1...100)
cancellable = numbers.publisher
.tryDrop {
guard $0 != 0 else { throw RangeError() }
return range.contains($0)
}
.sink(
receiveCompletion: { print ("completion: \($0)") },
receiveValue: { print ("value: \($0)") }
)
// Prints: "-1 7 8 9 10 completion: finished"
// If instead numbers was [1, 2, 3, 4, 5, 6, 0, -1, 7, 8, 9, 10], tryDrop(while:) would fail with a RangeError.
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift Result.Publisher tryLast(where:)用法及代码示例
- Swift Result.Publisher tryCompactMap(_:)用法及代码示例
- Swift Result.Publisher tryCatch(_:)用法及代码示例
- Swift Result.Publisher tryReduce(_:_:)用法及代码示例
- Swift Result.Publisher tryFilter(_:)用法及代码示例
- Swift Result.Publisher tryFirst(where:)用法及代码示例
- Swift Result.Publisher tryPrefix(while:)用法及代码示例
- Swift Result.Publisher tryScan(_:_:)用法及代码示例
- Swift Result.Publisher tryMap(_:)用法及代码示例
- 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 tryDrop(while:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。