假设我们有一个
Swift协议:
protocol SomeProtocol: class { static var someString: String { get } }
有没有办法从扩展实例方法访问someString,像这样?
extension SomeProtocol { public func doSomething() -> String { return "I'm a \(someString)" } }
我收到编译器错误:
Static member ‘someString’ cannot be used on instance of type ‘Self’
有没有办法实现这个目标?
你需要用Self引用someString(注意大写的S):
extension SomeProtocol { public func doSomething() -> String { return "I'm a \(Self.someString)" } }