让我们看一个理论示例:
protocol Text {} //Protocol in the external Framework
extension String: Text {} //Implementing the protocol in the app
protocol A { //Another protocol in the external Framework
var text: Text { get }
}
class B { //Existing class in the app, I'd like to pass where Framework expects protocol A
let text: String = ""
}
我尝试这样做:
//ERROR: Type 'B' does not conform to protocol 'A'
extension B: A {}
尝试在XCode中使用solve
函数会执行以下操作:
extension B: A {
//ERROR: Invalid redeclaration of 'text'
var text: Text {
...
}
}
我还能做什么?我想避免在class B
中更改变量名,因为它已经广泛使用,并且将是一个很大的重构。
我最终得到的是某种包装纸:
//1) Wrapper
class C: A {
let b: B
var text: Text {
return b.text
}
init(b: B) {
self.b = b
}
}
extension B {
var wrapper: A {
return C(b: self)
}
}
现在到外部Framwork期望类型为A
的任何地方,而不是通过b
而是通过b.wrapper
。
还有其他方法可以实现同一目标吗?对我来说,创建包装器似乎不是理想的解决方案。