Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
Dov Avatar asked Dec 15 '15 19:12

Dov


People also ask

Can Swift protocols have static methods?

Swift allows us to use a static prefix on methods and properties to associate them with the type that they're declared on rather than the instance. We can also use static properties to create singletons of our objects which, as you have probably heard before is a huge anti-pattern.

What is protocol extension in Swift?

An extension can extend an existing type to make it adopt one or more protocols. To add protocol conformance, you write the protocol names the same way as you write them for a class or structure: extension SomeType: SomeProtocol, AnotherProtocol { // implementation of protocol requirements goes here.

What is use of protocol in Swift?

Protocol is a very powerful feature of the Swift programming language. Protocols are used to define a “blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”

What is protocol iOS?

In iOS development, a protocol is a set of methods and properties that encapsulates a unit of functionality. The protocol doesn't actually contain any of the implementation for these things; it merely defines the required elements.


1 Answers

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

extension SomeProtocol {
    public func doSomething() -> String {
        return "I'm a \(Self.someString)"
    }
}
like image 94
Dov Avatar answered Oct 09 '22 12:10

Dov