13: 喬喬 Erasure

又是歡樂的一集!今天聊起 #weakself挑戰賽的 Type Erasure 與 Opaque Return Type。不過,怎麼某人的聲音到後半段就 erased 了!?

{ 完整節目筆記請按我 }

前言

我恨 PAT

PAT 是什麼?看 code

PAT 三不能:

  • 不能做為變數型別用
  • 不能做為 function 的 return
  • 不能放在 Collection 裡

你是忘記還是害怕想起:
compile error

Type Erasure 為何而生

PAT 難搞的地方有兩種:

  1. Self 的 Protocol:Hashable
  2. associatedtype 的 Protocol:IteratorProtocol

對應的做法:

  1. AnyHashable: 黑魔法 C++
  2. AnyIterator: 用 generic struct 解決
    範例請見這裡
  3. 對 AnyHashable 有興趣請右轉

Opaque Return Type

  • weakself 的中文名稱是個 Opaque Type (Caller 決定 generic 是什麼)
  • Opaque Return Type 則由 Callee 決定 generic 是什麼
  • 避免 generiception:
public typealias LazyCompactMapCollection<Elements, ElementOfResult>
 -> <C: Collection> C where C.Element == ElementOfResult
 = LazyMapSequence<LazyFilterSequence<LazyMapSequence<Elements, ElementOfResult?>>, ElementOfResult>

那第三個問題,不能把 PAT 放入 collection 呢?

抱歉,還無法🤷‍♂️

更多 weak self

Om Podcasten

在 iOS 開發圈打滾的台灣工程師,專為 Apple & iOS 開發者而製作的中文 Podcast。內容涵蓋 Apple 開發圈的新知討論、踩坑經驗、人物採訪、社群活動、職場生活。更多資訊請見官網 https://weakself.dev 或是 Twitter @weak_self -- Hosting provided by SoundOn