为什么以下代码会产生错误?
protocol ProtocolA {
var someProperty: ProtocolB { get }
}
protocol ProtocolB {}
class ConformsToB: ProtocolB {}
class SomeClass: ProtocolA { // Type 'SomeClass' does not conform to protocol 'ProtocolA'
var someProperty: ConformsToB
init(someProperty: ConformsToB) {
self.someProperty = someProperty
}
}
Run Code Online (Sandbox Code Playgroud)
这个类似问题的答案是有道理的.但是,在我的示例中,属性是get-only.为什么不能这样做?它是Swift的缺点,还是有一些合理的理由?
是否可以通过扩展将协议合规性添加到不同的协议?
例如,我们希望A符合B:
protocol A {
var a : UIView {get}
}
protocol B {
var b : UIView {get}
}
Run Code Online (Sandbox Code Playgroud)
我想给B类的对象提供B的默认实现(合规性)
// This isn't possible
extension A : B {
var b : UIView {
return self.a
}
}
Run Code Online (Sandbox Code Playgroud)
动机是在需要B的情况下重用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) {
...
... …Run Code Online (Sandbox Code Playgroud)