2: Swift API 設計之原來我不會用 protocol

weak self

2019-08-0400:37:42

Available Platforms

主題延續上一集的 Swift API 設計,進入了 protocol 與 generic 的領域。
{ 完整節目筆記 https://weakself.dev/episodes/2 }
前情提要
CJ 同學提出了一個好問題:「Value type 在某些時刻,會存在 heap 中?」波肥寫了一篇 blog 文章來回答。
Protocol 是什麼?

Protocol-Oriented Programming in Swift (WWDC 2015)

Protocol 也有兩種

Protocol 的 Existentail Container 與其結構
Opaque Result Type

POP 要解決什麼問題?

Duck Typing

比起繼承,要多愛用 Protocol 組合

標準函式庫裡的 protocols
Array 的 Protocol Hierarchy 視覺呈現 (Swift 4.2)

Protocol 使用指南

先寫 concrete type
是否有已存在的 protocol 可以 extension
是否可由已存在的 protocol 組合完以成功能
優先考慮 Generic ,最後才是創造一個新的 protocol


一個簡單的用 generic struct 取代 protocol 的例子。

隨堂小測驗

兩者之間有什麼差異?

尾聲

小綠同學討論 forEach 與 for in
歡迎訂閱«13 的開發者週報»

更多 weak self

主講人 一三、波肥、喬喬
官網 https://weakself.dev
Twitter @weak_self
提問箱
Comments