实例方法
try
tryScan(_:_:)
通过将当前元素与闭包返回的最后一个值一起提供给 error-throwing 闭包来转换来自上游发布者的元素。
声明
func tryScan<T>(
_ initialResult: T,
_ nextPartialResult: @escaping (T, Self.Output) throws -> T
) -> Publishers.TryScan<Self, T>
返回值
一个发布者,它通过应用一个闭包来转换元素,该闭包接收其先前的返回值和来自上游发布者的下一个元素。
参数
initialResult
nextPartialResult
闭包返回的先前结果。nextPartialResult
一个 error-throwing 闭包,它的参数是闭包返回的前一个值和上游发布者发出的下一个元素。
详述
使用 Publisher/tryScan(_:_:)
将所有 previously-published 值累积为单个值,然后将其与每个 newly-published 值组合。如果您的累加器闭包引发错误,则发布者会因错误而终止。
在下面的示例中,Publisher/tryScan(_:_:)
对集合发布者的元素调用除法函数。 Publishers/TryScan
发布者发布每个结果,直到函数遇到 DivisionByZeroError
,这会终止发布者。
struct DivisionByZeroError: Error {}
/// A function that throws a DivisionByZeroError if `current` provided by the TryScan publisher is zero.
func myThrowingFunction(_ lastValue: Int, _ currentValue: Int) throws -> Int {
guard currentValue != 0 else { throw DivisionByZeroError() }
return (lastValue + currentValue) / currentValue
}
let numbers = [1,2,3,4,5,0,6,7,8,9]
cancellable = numbers.publisher
.tryScan(10) { try myThrowingFunction($0, $1) }
.sink(
receiveCompletion: { print ("\($0)") },
receiveValue: { print ("\($0)", terminator: " ") }
)
// Prints: "11 6 3 1 1 -1 failure(DivisionByZeroError())".
如果闭包抛出错误,则发布者会因错误而失败。
可用版本
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 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 tryScan(_:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。