[英]Swift Class Extension Only When Conforming to Protocol
是否可以提供僅為符合協議的類添加功能的擴展? 我想要實現的功能是這樣的:
protocol Identifiable {
var id: String { get }
}
class Model {
func report(data: String) {
...
}
}
class Thing: Model, Identifiable {
var id: String
...
}
class Place: Model, Identifiable {
var id: String
...
}
extension (Model + Identifiable) {
func identifiy() {
report("\(self.id)")
}
}
// Invalid: Model().identify()
Place().identify() // OK
Thing().identify() // OK
無法擴展協議本身,因為擴展需要訪問model
定義的方法。 擴展模型失敗,因為id
僅在子對象上定義。 擴展Model: Identifiable
失敗,因為Model
不符合協議可Identifiable
。
您可以擴展Identifiable
,您只需要指定Self
是Model
或Model
子類:
extension Identifiable where Self: Model {
func identifiy() {
report(id)
// `id` is already a `String` so there's
// no need to use String Interpolation.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.