问题
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?
回答1:
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?
}
回答2:
Remark: If you are unsure that inheritance the is right choice for your case, I suggest to check Sulthan's answer.
However, As you mentioned, Swift does not support multiple inheritance. What you should do instead is to let Address
class adopts protocols; You can also add Protocol Extensions:
You can extend an existing type to adopt and conform to a new protocol, even if you do not have access to the source code for the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol may demand.
means that you can implement default values/behaviors to a protocol methods/properties.
Referring to your example, it should be similar to:
protocol City { }
extension City {
var cityId: String {
return "Default City ID"
}
var cityName: String {
return "Default City Name"
}
// adding method:
func doSomething() {
print("Do Something!!")
}
}
protocol Town { }
extension Town {
var townid: String {
return "Default Town ID"
}
var townName: String {
return "Default Town Name"
}
}
class Address:City, Town {}
Output:
let address = Address()
print(address.cityId) // Defaut City ID
print(address.cityName) // Defaut City Name
print(address.townid) // Default Town ID
print(address.townName) // Default Town Name
address.doSomething() // Do Something!!
Also, if you want to add some additional job to a method (similar to super.doSomething()
), you do it like this:
class Address:City, Town {
func doSomething() {
(self as City).doSomething()
print("Addtional Job!!")
}
}
Output:
let address2 = Address()
address2.doSomething()
// Do Something!!
// Addtional Job!!
Take it Further:
For more information, check Protocols and Extensions Documentations.
Also, you might want to watch Protocol-Oriented Programming in Swift Apple Session.
来源:https://stackoverflow.com/questions/43086544/swift-does-not-support-multiple-inheritance-how-could-be-achieved