从协议扩展实例方法中读取静态变量
Reading static var from protocol extension instance method
假设我们有一个 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'
有什么办法可以做到吗?
你需要参考someString
和Self
(注意大写S
):
extension SomeProtocol {
public func doSomething() -> String {
return "I'm a \(Self.someString)"
}
}
假设我们有一个 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'
有什么办法可以做到吗?
你需要参考someString
和Self
(注意大写S
):
extension SomeProtocol {
public func doSomething() -> String {
return "I'm a \(Self.someString)"
}
}