In programming languages of the C family (including Objective-C), there have always been "class methods". In Swift, two types of such methods for types have appeared — static and class. They allow calling methods on the type itself rather than on an instance. Static is used for structs, enums, and classes strictly without the possibility of overriding, while class is for classes that allow overriding in subclasses.
Problem: Confusion between static and class arises in class hierarchies where inheritance is possible, and there is a desire to allow or disallow method/property overriding for descendants.
Solution:
Example code:
class Animal { class func makeSound() { print("Some generic animal sound") } static func kingdom() -> String { "Animalia" } } class Dog: Animal { override class func makeSound() { print("Woof!") } // override static func kingdom() — error: static cannot be overridden! } Animal.makeSound() // Some generic animal sound Dog.makeSound() // Woof! print(Animal.kingdom()) // Animalia
Key features:
Can you use class func in structs or enums?
No, class func is only allowed for classes. Structs and enums only support static methods and properties.
Can static property be computed and/or mutable (var)?
Yes, static property can be both computed and stored and can be defined through static var. For structs and enums, this is the only way to make a property available through the type itself, not the instance.
Example code:
struct Counter { static var totalCount = 0 static var nextId: Int { totalCount += 1 return totalCount } }
Can you call a class method through an instance of the class?
Yes, but it is not recommended: a class method always relates to the type itself, not a specific object, so the behavior of the base type or its overrides will be called, which has no relation to a specific object.
Using class func for static utility methods of a class, although no overriding is intended.
Pros:
Cons:
Using static for constants and utilities, class — for factory methods that may indeed be changed in subclasses.
Pros:
Cons: