Swift Type Methods: Static vs Class
A few days ago while reading the Swift 2.2 documentation, I came upon the section discussing Type Methods. Swift allows one to define methods for instances of a type and the types themselves. The types can be classes, structures, or enumerations, etc.
Two keywords are associated with defining and declaring type methods:
- static
- class
Which one to choose when dealing with classes comes down to whether or not one wants to allow a subclass to override the method. The following examples illustrate the use of static and class for type methods:
import Foundation
class SomeClass {
static func someClassMethod() {
}
}
class AnotherClass {
class func someClassMethod() {
}
}
class SubClass: AnotherClass {
override class func someClassMethod() {
}
// compiles fine
}
The code above does not tick off the compiler. The following code will:
import Foundation
class SomeClass {
static func someClassMethod() {
}
}
class AnotherClass {
class func someClassMethod() {
}
}
class SubClass: SomeClass {
override static func someClassMethod() {
}
// compiler error message: class method overrides a 'final' class method
}
At the end of the day it comes down to design choice. If one does not intend for subclasses to muck around with the innards of the class-level methods, make them static. Otherwise, consider using class to allow the flexibility to override the parent implementation or add to the method like the following snippet:
import Foundation
class SomeClass {
static func someClassMethod() {
}
}
class AnotherClass {
class func someClassMethod() {
}
}
class SubClass: AnotherClass {
override class func someClassMethod() {
super.someClassMethod()
// more code here...
}
}