Search code examples
swiftoopinheritancemultiple-inheritance

Swift does not support multiple inheritance, How could be achieved?


The following code:

class City {
    var cityId : String?
    var cityName : String?
}

class Town {
    var townid : String?
    var townName : String?

}

class Address : City , Town {

    var house : String?
    var street: String?

}

Generates a compile-time error:

Address.swift:38:24: Multiple inheritance from classes 'City' and 'Town'

How can I solve his kind of problem? What approach to follow?


Solution

  • It seems you are overthinking things. Instead of inheritance, try to use more composition. An address should not inherit from City. Why? Because logically an address is not a type of city. Instead, city definition is part of the address:

    class Address { 
        var city: City?
        var town: Town?
    
        var house : String?
        var street: String?
    }