Dov
Dov

Reputation: 16156

Reading static var from protocol extension instance method

Let's say we have a Swift protocol:

protocol SomeProtocol: class {
    static var someString: String { get }
}

Is there a way to access someString from an extension instance method, like so?

extension SomeProtocol {
    public func doSomething() -> String {
        return "I'm a \(someString)"
    }
}

I get a compiler error:

Static member 'someString' cannot be used on instance of type 'Self'

Is there any way to accomplish this?

Upvotes: 6

Views: 1066

Answers (1)

Dov
Dov

Reputation: 16156

You need to refer to someString with Self (note the uppercase S):

extension SomeProtocol {
    public func doSomething() -> String {
        return "I'm a \(Self.someString)"
    }
}

Upvotes: 6

Related Questions