Software Engineering
class enum static-methods swift-language
Updated Fri, 19 Aug 2022 15:20:34 GMT

Static properties and implicit "self" property in structures and enumerations vs classes in Swift


I am currently reading the Swift language documentation and came across these sentences in the chapter about methods:

Similarly, type methods on structures and enumerations can access static properties by using the static property's name without a type name prefix.

Within the body of a type method, the implicit self property refers to the type itself, rather than an instance of that type. For structures and enumerations, this means that you can use self to disambiguate between static properties and static method parameters.

I was under the impression that these rules are also valid for classes and instances of classes. My question is, why are only structs and enums being mentioned? Is this just an accidental omission in the documentary or do different rules indeed apply for classes and their instances?




Solution

I expect the reason is because the example presented is a class, so the authors felt it was important to call out the fact that this works with structs and enums as well.

The latest version of the book has reworded that passage:

More generally, any unqualified method and property names that you use within the body of a type method will refer to other type-level methods and properties. A type method can call another type method with the other methods name, without needing to prefix it with the type name. Similarly, type methods on structures and enumerations can access type properties by using the type propertys name without a type name prefix.

-- The Swift Programming Language (emphasis added by me.)