為 Protocol 採用的 Protocol 提供預設實作 — 緣起

Li-Hsuan Chen
Jul 25, 2017 · 2 min read

在我們公司的專案中,為了提高可測試性、降低各個類別之間的相依,我們高度的抽象化我們所寫出來的類別。
也就是說,我們採用了 POP (Protocol oriented programming) 的原則,一切以介面 (Protocol) 的定義為開始設計,各個物件之間的互動,也都是透過介面互動。

於是,在 Model 層的地方,我們想要依循 best practices 之中,那個大家都在建議的:「 Model 至少應該要繼承 Equatable 這個 protocol 」。

再者,我們就希望 Equatable 可以放在 Protocol 這個抽象介面的地方,而非實做出來的 struct ,並透過 extension Protocol 的提供預設實作,讓採用這個 Protocol 的不管是正式專案裡的 struct 或是測試案例裡面的 mock 類別或結構,都可以直接無痛的享用到這個 Protocol extension 所提供的 Equatable 預設實作,不用再重新寫一次。

於是就直覺的寫了這樣的一個東西:

protocol ProductType {}extension ProductType: Equatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.name == rhs.name
}
}

然後 Xcode 就會開始抱怨:

Extension of protocol ‘ProductType’ cannot have an inheritance clause

簡單講就是你不能這樣做,
然後我就開始抱頭了。

~待續~

Li-Hsuan Chen

An iOS engineer who came from Changhua, Taiwan and located in Tokyo right now. Interested in architecture design, UI/UX design and cross domain things.

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