Trevör Anne Denise Trevör Anne Denise - 6 months ago 16
Swift Question

Why is it recommended to prefix property requirements with static in Swift protocols?

In the Swift documentation section about Protocols, it is written that :


Always prefix type property requirements with the
static
keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the
class
or
static
keyword when implemented by a class


I don't understand if you should always do that or just in specific cases (because later in the docs,
static
isn't always there).

Why is it recommended to use
static
? What does it mean concretely?

Thank you.

EDIT : The same question applies to methods requirements.

Answer

later in the docs, static isn't always there

This section talks about type requirement, i.e. a requirement of the conforming type to have a static property of the specific name and type. In other words, when you write this

protocol MyProtocol {
    static var myProperty: Int { get set }
}

the conforming class must do this

class MyClass : MyProtocol {
    static var myProperty: Int
}// ^^^^^^

It also has an option to do this:

class MyClass : MyProtocol {
    class var myProperty: Int
}// ^^^^^

but there is no such option when defining a protocol.

When static is not used, as happens later in the docs, the requirement becomes an instance requirement, not a type requirement:

protocol MyProtocol2 {
   var myProperty2: Int { get set }
}

Now the class must provide an instance variable:

class MyClass2 : MyProtocol2 {
    var myProperty2: Int
}

Note that there is a similar limitation on declaring instance requirements in protocols: you always use var, even though an implementation may use let to satisfy the requirement:

protocol MyProtocol3 {
    var myProperty3: Int { get }
}// ^^^
class MyClass3 : MyProtocol3 {
    let myProperty3 = 42
}// ^^^