為 Protocol 採用的 Protocol 提供預設實作 — extension 的限制和解法

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

上一回的緣起中有提到 Protocol 的 extension 沒有辦法幫另外一個 Protocol 提供預設實作。原因是 Swift 不允許 Protocol 的 extension 去繼承另外一個 Protocol 。


很簡單的解法就是把對另外一個 Protocol 的使用,提升到 Protocol 宣告的地方即可:

protocol ProductType: Equatable {} // ← 移動到這裡extension ProductType {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.name == rhs.name
}
}

但是這樣子就有一個缺點,這個 extenstion 就很難看出來他是什麼的實作:是從零開始自己的定義?還是其實是實作某個 Protocol 裡面的方法?

目前有想到比較好的解法就是加上 MARK 來標示:

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

Li-Hsuan Chen

Written by

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