I'm coming from a dynamic language background, and struggling to wrap my head around inheritance best practices.
Specifically, I have a ChildClass
that I wish to act as a singleton via:
class ChildClass: ParentClass {
static var myInstance: ChildClass = ChildClass
private init() {}
}
It overrides:
class ParentClass: ParentClassProtocol, Identifiable, Encodable {
static var myInstance: ParentClass = ParentClass()
private init() {}
// ...lotsa of other methods & variables....
}
The ChildClass 'myInstance' returns a 'cannot override with a stored property 'myInstance'
error
From what I understand, the agreed way to get around this is to implement ChildClass and ParentClass by a common protocol, and have ChildClass inherit from ParentClassProtocol
instead of ParentClass
.
I'm happy to do that, except ParentClassProtocol
has a lot of methods that would have duplicate logic in ChildClass
...which would be a pretty egregious violation of DRY principles and cause headaches should I forget to change the code in both places in the future.
I suspect I'm misunderstanding best practices here relating to protocols, but I can't figure out how. So in short:
If you had a ParentClass
and a ChildClass
, and you wanted to ensure different default values for a common declared variable, what are best practices? (And if it's protocols, how do you avoid duplicating all other variables/functions in the method?'