实例方法
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 Optional.Publisher tryDrop(while:)用法及代码示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代码示例
- Swift Optional.Publisher tryReduce(_:_:)用法及代码示例
- Swift Optional.Publisher tryPrefix(while:)用法及代码示例
- Swift Optional.Publisher tryFirst(where:)用法及代码示例
- Swift Optional.Publisher tryFilter(_:)用法及代码示例
- 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 tryScan(_:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。