Search code examples
swiftinheritancesubclasssuperclass

accessing a subclass function from a superclass


Is there a way to access subclass methods from a superclass? The switch statement is in a function in the superclass. The functions createCityOne(), createCityTwo() and createCityThree() etc are each in their own subclasses.

    if transitionSprite.name == nil || transitionSprite.name == "rd-d2c" || transitionSprite.name == "rd-f2c" || transitionSprite.name == "rd-c2c" {
        print("city should come next")
        switch randomIndex {
        case 0:
            cityOne.createCityOne()
            print("1")
        case 1:
            cityTwo.createCityTwo()
            print("2")
        case 2:
            print("3")
            cityThree.createCityThree()
        default:
            break
        } 

Solution

  • You can't directly access subclass methods from superclass because superclass doesn't know anything about it's own subclasses.

    Although, you can always try casting things into things in Swift to get functionality of some other class.

    Take a look at this example. It's very basic and simple but I hope you get the idea.

    So imagine you have a class City:

    class City {
        func build() {
            print("city is building")
    }
    

    And it's subclass Town:

    class Town: City {
        func buildTown() {
            print("town is building")
        }
    }
    

    Now you want to have an access to Town's buildTown() function from the City class. Because Town will always be a City as it's subclass you could create something like this:

    class City {
        func build() {
            print("city is building")
        }
    
        func buildAnything() {
            if self is Town {
                (self as! Town).buildTown()
            }
        }
    }
    

    Now I'm not saying that you would really want to create something like this because you expose logic of a subclass to a superclass that way. So a good way to solve this would be creating only one build() function and then overriding it.

    class City {
        func build() {
            print("city is building")
        }
    }
    
    class Town: City {
        override func build() {
            print("town is building")
        }
    }
    

    As result, you can access the same function from any City subclass you want and customize the behavior.

    let myTown = Town()
    let myCity = City()
    myCity.build() //prints "city is building"
    myTown.build() //prints "town is building"
    

    The good solution is always depends on your exact goals so always look at many options the language provide. More on inheritance here.