iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

30 天了解 Swift 的 Combine系列 第 10

30 天了解 Swift 的 Combine: [10] Operator 2: 一般篩選類型

1.filter 只將通過條件的上游持續發布

就像是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-----|

2. compactMap 專為 enum Optional 篩選並抹除 Optional

使用 元素轉換閉包 返回 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-----------|

3. removeDuplicates 篩去上游重覆發布的元素

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--|

簡單測驗

  1. 使用 scan 實作 removeDuplicates
  2. removeDuplicates() 的 Output 需符合 Equatable,要實作什麼內容?

whoami:
我是游諭 ytyubox


上一篇
30 天了解 Swift 的 Combine: [09] Operator 目錄 + 第一部分:轉換類型
下一篇
30 天了解 Swift 的 Combine: [11] Operator 3.整併類型 + 4.符合篩選類型 + 5.序列篩選類型
系列文
30 天了解 Swift 的 Combine30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言