I can see these definitions in the Swift library:
extension Bool : BooleanLiteralConvertible {
static func convertFromBooleanLiteral(value: Bool) -> Bool
}
protocol BooleanLiteralConvertible {
typealias BooleanLiteralType
class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self
}
What's the difference between a member function defined as static func
and another one defined as class func
? Is it simply that static
is for static functions of structs and enums, and class
for classes and protocols? Are there any other differences that one should know about? What is the rationale for having this distinction in the syntax itself?
According to the Swift 2.2 Book published by apple:
“You indicate type methods by writing the
static
keyword before the method’s func keyword. Classes may also use theclass
keyword to allow subclasses to override the superclass’s implementation of that method.”I did some experiments in playground and got some conclusions.
TL;DR
As you can see, in the case of
class
, the use ofclass func
orstatic func
is just a question of habit.Playground example with explanation:
This is called type methods, and are called with dot syntax, like instance methods. However, you call type methods on the type, not on an instance of that type. Here’s how you call a type method on a class called SomeClass:
Source: The Swift Programming Language - Type Variable Properties
That's the main difference. Some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.
Protocols use the class keyword, but it doesn't exclude structs from implementing the protocol, they just use static instead. Class was chosen for protocols so there wouldn't have to be a third keyword to represent static or class.
From Chris Lattner on this topic:
And here's a snippet that shows some of the override behavior of class functions:
From Swift2.0, Apple says:
"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:"