Reputation: 3952
I've started working through a textbook that talks about protocol oriented programming in Swift. As I'm writing out the code in a playground I noticed that one of the methods from the book uses the keyword 'static'. To my understanding, a static method means that this method is to be called by the type itself and not by specific instances of the type. Also my understanding is that, static methods can't be overridden.
Since protocols are only method signatures when their being declared, I thought it was kind of odd to see the keyword 'static' being used because we'll have to implement the stub of the function when we conform to the protocol anyway.
To start thinking in an abstract way, I'd like to know if protocol methods are meant to be overridden in Swift or does the use of the keyword 'static' simply makes it to where only the type itself can call a method versus its instances calling the method?
protocol YourProtocol {
//property requirements that types that conform to this protocl MUST implement
var gettableProperty: String { get }
var gettableSettableProperty: Int { get set }
//method requirements that types that conform to this protocol MUST implement
func someMethod(parameter1: Double) -> String
static func staticMethod() -> Float
}
Upvotes: 0
Views: 49
Reputation: 130102
You are right that static
methods cannot be overriden because they are always tied to one specific type, however, a static
method declaration in a protocol can be implemented using a class
method. And class
methods can be overriden:
protocol YourProtocol {
static func staticMethod() -> Float
}
class A: YourProtocol {
class func staticMethod() -> Float {
return 1.0
}
}
class B: A {
override class func staticMethod() -> Float {
return 2.0
}
}
Also, the ability to be overriden is not the core point. I think the concept can be better understood on a static
constant or a static
variable getter, taking an example from the static library:
public protocol FloatingPoint: ... {
public static var pi: Self { get }
}
This protocol is implemented by all floating point types, e.g. Double
and Float
which are not even classes therefore they don't support inheritance and overriding. The fact that even their static constants are declared in a protocol can be then used when declaring a generic method that uses this protocol as a type constraint:
func toDegrees<T: FloatingPoint>(radians: T) -> T {
// the .pi here is a static var getter
return radians * 180 / T.pi
}
Upvotes: 2