It is easy to override a method in Swift:
class A {
func innerValue() -> Int { return 5 }
func getInnerValue() -> Int { return innerValue() }
}
class B: A {
override func innerValue() -> Int { return 8 }
}
B().getInnerValue() //returns 8
However I don't know how to do the same when I declare innerValue()
as static (using the class
keyword):
class A {
class func innerValue() -> Int { return 5 }
func getInnerValue() -> Int {
return A.innerValue() //ok for compiler but returns 5 instead of 8
return self.innerValue() //error: 'A' doesn't have a member named 'innerValue'
return innerValue() //error: Use of unresolved identifier 'innerValue'
}
}
class B: A {
override class func innerValue() -> Int { return 8 }
}
B().getInnerValue()
So is it possible in Swift?
return A.innerValue() //ok for compiler but returns 5 instead of 8
From your comment, it sounds like what you want to do is refer the current instance's class polymorphically. If that's what you want, then don't send the innerValue()
message to A
; that means A
only. And don't send it to self
, because the way you've written this, getInnerValue
is an instance method, while what you want to call is a class method. Send it to self.dynamicType
, the class of the current instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With