Swift — map & flatMap

T.c. Hung
T.c. Hung
Aug 23, 2017 · 2 min read

關於 map & flatMap 把網路上的一些資源做重點整理

Reference :

Swift 燒腦體操:http://www.infoq.com/cn/articles/swift-brain-gym-map-and-flatmap

應用範例:http://blog.xebia.com/the-power-of-map-and-flatmap-of-swift-optionals/

Monad & Functor 圖解:http://www.ruanyifeng.com/blog/2015/07/monad.html

Array 有一種map函數,兩種flatMap函數:

當map的閉包返回值,不是Sequence type時,和flatMap的差異就僅在於是否判斷結果為nil。

圖片來源:Sai Li @ Swift Taipei

Optional 有一種map函數,一種flatMap函數:

兩者本質上一樣,提供調用者閉包函數,可返回Optional值,也可以是非Optional值。

圖片來源:Sai Li @ Swift Taipei

Array 和 Optional 的 map 函數都叫一樣的名字,是因為他們都是 Functor

Array 和 Optional 的 flatMap 函數都叫一樣的名字,是因為他們都是 Monad

圖片來源:Sai Li @ Swift Taipei
Functor 圖解 — Functor 的函数定義是輸入「未封裝的值」到輸出「未封裝的值」
Monad 圖解 — Functor 的函数定義是輸入「未封裝的值」到輸出「封裝後的值」

Swift X TeChengHung

Programmer

)

T.c. Hung

Written by

T.c. Hung

iOS Developer @TW (=゚ω゚)ノ https://twitter.com/dan_phy1988

Swift X TeChengHung

Programmer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade