UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Understanding inheritance in child classes

Forums > Swift

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?'

2      

class Parent:  Identifiable, Encodable {
    init() { }
    func who(){print("PARENT")}
    // ...lots of other methods & variables....
}

class ParentClone:  Parent {
    static let singleton = ParentClone()
    // No methods or instance variables.
}

class Child: Parent {
    static let singleton = Child()
    override init() { } // Delete if child does not need different init.
    override func who(){print("CHILD")}
}

Child.singleton.who()
ParentClone.singleton.who()

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.