是否可以通过扩展将协议合规性添加到不同的协议?
例如,我们希望 A 遵守 B:
protocol A {
var a : UIView {get}
}
protocol B {
var b : UIView {get}
}
我想为 A 类型的对象提供 B 的默认实现(合规性)
// This isn't possible
extension A : B {
var b : UIView {
return self.a
}
}
动机是在不需要创建我自己的“桥梁”的情况下重用 A 的对象
class MyClass {
func myFunc(object : A) {
...
...
let view = object.a
... do something with view ...
myFunc(object) // would like to use an 'A' without creating a 'B'
}
func myFunc2(object : B) {
...
...
let view = object.b
... do something with view ...
}
}
作为旁注,我们可以扩展一个类来实现协议
class C {
let C : UIView
}
// this will work
extension C : B {
var B : UIView {
return self.c
}
}
和协议可以给出默认实现
extension A {
// a default implementation
var a : UIView {
return UIView()
}
}