To factorize my code, I want to set a stringKey from an Child class which I'll get in a class func in the parent class:
Chair.request();
Table.request();
class Furniture: NSObject {
static let requestKey : String!
class func request(){
print("class key => \(self.requestKey)")
...
}
}
class Chair: Furniture {
static let requestKey : String = "jsonchairs"
}
class Table: Furniture {
static let requestKey : String = "tables"
}
Of course, I have the precompiled error message
Property does not override any property from its superclass
Is there a solution to do this, or do I need to pass the key as parameter? like this:
Chair.request(key : "jsonchairs" );
Table.request(key : "tables" );
You can have a member variable such as furnitureType, and can override that in the initialiser of repective subclasses.
Where static and class differ is how they support inheritance: When you make a static property it becomes owned by the class and cannot be changed by subclasses, whereas when you use class it may be overridden if needed. SPONSORED Want to explore your Swift skill outside of the Apple world?
Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.
data segment stores Swift static variables, constants and type metadata.
Just had the same problem. Use computed properties - these can be overriden.
Base class:
class BaseLanguage {
class var language: String {
return "Base"
}
static func getLocalized(key: String) -> String {
print("language: \(language)");
}
}
Child class:
class German: BaseLanguage {
override class var language: String {
return "de"
}
}
If you can't use computed properties for some reason, you can always wrap variable properties in private singleton. The class exposes external interface as as static, but inside it has static private reference to its instance. You can change value of any property (as long as it's variable) within init method.
You can use protocols for that. Just make them both conform to RequestKeyProtocol fir example and than implement it in each case.
protocol RequestKeyProtocol {
var requestKey: String
}
class myClass: RequestKeyProtocol {
var requestKey = "myKey"
}
If you need a default value look into protocols extensions. Take a look at this year WWDC video about protocols as well.
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