Operator之元素过滤(Filtering elements)
compactMap/tryCompactMap
compactmap可用于过滤nil
[1, 2, nil, 3, nil, 4, nil, 5].publisher
.compactMap { $0 }
.sink(receiveValue: { int in
print("Received \(int)")
})
同样,tryCompactMap
在compactMap
的基础上,允许在闭包中抛出异常。
filter/tryFilter
筛选了数字大于8的所有结果
_ = [5, 10, 25]
.publisher
.filter { value in
value > 8
}
.sink(receiveCompletion: { _ in
print("结束了")
}, receiveValue: { someValue in
print(someValue)
})
removeDuplicates/tryRemoveDuplicates
滤掉重复的数据
_ = [1, 1, 1, 2, 2, 3]
.publisher
.removeDuplicates()
.sink(receiveCompletion: { _ in
print("结束了")
}, receiveValue: { someValue in
print(someValue)
})
如果publisher输出的数据不实现Equatable
协议,则使用以下方式指定规则
.removeDuplicates(by: { first, second -> Bool in
// your logic is required if the output type doesn't conform to equatable.
first.id == second.id
})
replaceEmpty/replaceNil/replaceError
replaceEmpty(with:)
使用 replaceEmpty(with:) 操作符来替换一个值(如果发布者完成了但没有发出一个值)。
// 1
let empty = Empty<Int, Never>()
// 2
empty
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &subscriptions)
replaceNil(with:)
replaceNil
将接收可选值并将 nil
替换为您指定的值
["A", nil, "C"].publisher // 1
.eraseToAnyPublisher()
.replaceNil(with: "-") // 2
.sink(receiveValue: { print($0) }) // 3
.store(in: &subscriptions)
replaceError(with:)
replaceError
能够捕获pipline中的任何异常,并返回一个默认值。当我们的数据流模型不想接受任何Error的场景下,可以考虑使用replaceError。
使用catch
也能够实现replaceError
同样的功能:
.catch { err in
return Just(0)
}