實例方法
try
tryRemoveDuplicates(by:)
僅發布與前一個元素不匹配的元素,由提供的 error-throwing 閉包評估。
聲明
func tryRemoveDuplicates(by predicate: @escaping (Self.Output, Self.Output) throws -> Bool) -> Publishers.TryRemoveDuplicates<Self>
返回值
使用(而不是發布)重複元素的發布者。
參數
predicate
用於評估兩個元素是否等效的閉包,用於過濾。從此閉包中返回
true
以指示第二個元素是第一個元素的副本。如果此閉包拋出錯誤,則發布者會以拋出的錯誤終止。
詳述
使用 Publisher/tryRemoveDuplicates(by:)
根據您提供的 error-throwing 閉包對元素的評估,從上遊發布者中刪除重複元素。如果您的閉包引發錯誤,則發布者會因錯誤而終止。
在下麵的示例中,提供給 Publisher/tryRemoveDuplicates(by:)
的閉包在兩個連續元素相等時返回 true
,從而過濾掉 0
、 1
、 2
和 3
。但是,閉包在遇到 4
時會引發錯誤。然後發布者終止並出現此錯誤。
struct BadValuesError: Error {}
let numbers = [0, 0, 0, 0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
cancellable = numbers.publisher
.tryRemoveDuplicates { first, second -> Bool in
if (first == 4 && second == 4) {
throw BadValuesError()
}
return first == second
}
.sink(
receiveCompletion: { print ("\($0)") },
receiveValue: { print ("\($0)", terminator: " ") }
)
// Prints: "0 1 2 3 4 failure(BadValuesError()"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Optional.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代碼示例
- 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 tryContains(where:)用法及代碼示例
- Swift Optional.Publisher tryCompactMap(_:)用法及代碼示例
- 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 tryRemoveDuplicates(by:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。