是否有可能提供只向符合协议的类添加功能的扩展?我想要实现的功能如下:
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。
发布于 2015-09-08 00:29:40
您可以扩展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.
}
}https://stackoverflow.com/questions/32447502
复制相似问题