就像是if then,沒有 else 而已!
Declaration
func filter(_ isIncluded: @escaping (Self.Output) -> Bool) -> Publishers.Filter<Self>
isIncluded: 作為篩選的依據
******demo code*******
_ = (1...2).publisher
.filter{$0.isMultiple(of: 2)}
.sink{ print("get value:", $0)}
******console*********
get value: 2
*******Rarbles********
--1-----2-----|
filter{$0.isMultiple(of: 2)}
--------2-----|
使用 元素轉換閉包
返回 Optional,就可以了。
Calls a closure with each received element and publishes any returned optional that has a value.
Declaration
func compactMap<T>(_ transform: @escaping (Self.Output) -> T?) -> Publishers.CompactMap<Self, T>
transform 元素轉換閉包,不同於 map,是可回傳 Optional
******demo code*******
_ = ["1","a"].publisher
.compactMap{Int($0)}
.sink{ print("get value:", $0)}
******console*********
get value: 1
*******Rarbles********
--1-----a-----|
filter{$0.isMultiple(of: 2)}
--1-----------|
Declaration
func removeDuplicates() -> Publishers.RemoveDuplicates<Self>
Available when Output conforms to Equatable.
******demo code*******
_ = [1,1,2,1,3].publisher
.removeDuplicates()
.sink{ print("get value:", $0)}
******console*********
get value: 1
get value: 2
get value: 1
get value: 3
*******Rarbles********
--1--1--2--1--3--|
removeDuplicates
--1-----2--1--3--|
簡單測驗
whoami:
我是游諭 ytyubox