實例方法
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 Result.Publisher tryFilter(_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Result.Publisher tryPrefix(while:)用法及代碼示例
- Swift Result.Publisher tryScan(_:_:)用法及代碼示例
- 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 tryFirst(where:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。