如何在变量名与类中现有变量名相同的情况下实现协议?

时间:2019-11-20 11:27:13

标签: ios swift

让我们看一个理论示例:

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

还有其他方法可以实现同一目标吗?对我来说,创建包装器似乎不是理想的解决方案。

0 个答案:

没有答案