實例方法
try
tryContains(where:)
在接收到滿足拋出謂詞閉包的元素時發布布爾值。
聲明
func tryContains(where predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryContainsWhere<Self>
返回值
當上遊發布者發出匹配值時發出布爾值 true
的發布者。
參數
predicate
一個閉包,它接受一個元素作為其參數並返回一個布爾值,該值指示該元素是否滿足閉包的比較邏輯。
詳述
使用 Publisher/tryContains(where:)
查找上遊中滿足您提供的 error-throwing 閉包的第一個元素。
該運算符使用上遊發布者生成的元素,直到上遊發布者:
-
產生一個匹配元素,然後它發出
true
並且發布者正常完成。 -
如果沒有找到匹配的元素並且發布者正常完成,則發出
false
。
如果謂詞拋出錯誤,則發布者失敗,將錯誤傳遞給其下遊。
在下麵的示例中,Publisher/tryContains(where:)
運算符測試值以查找小於 10
的元素;當閉包找到奇數時,例如 3
,發布者以 IllegalValueError
終止。
struct IllegalValueError: Error {}
let numbers = [3, 2, 10, 5, 0, 9]
numbers.publisher
.tryContains {
if ($0 % 2 != 0) {
throw IllegalValueError()
}
return $0 < 10
}
.sink(
receiveCompletion: { print ("completion: \($0)") },
receiveValue: { print ("value: \($0)") }
)
// Prints: "completion: failure(IllegalValueError())"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Optional.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Optional.Publisher tryCatch(_:)用法及代碼示例
- 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 tryScan(_:_:)用法及代碼示例
- Swift Optional.Publisher tryFilter(_:)用法及代碼示例
- Swift Optional.Publisher tryMax(by:)用法及代碼示例
- Swift Optional.Publisher tryRemoveDuplicates(by:)用法及代碼示例
- Swift Optional.Publisher tryMap(_:)用法及代碼示例
- Swift Optional.Publisher tryLast(where:)用法及代碼示例
- Swift Optional.Publisher tryMin(by:)用法及代碼示例
- 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 tryContains(where:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。