Trevör Anne Denise Trevör Anne Denise - 2 years ago 76
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
keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the
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,
isn't always there).

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

Thank you.

EDIT : The same question applies to methods requirements.

Answer Source

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
}// ^^^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download