Swift 不支持多重继承,如何实现? [英] Swift does not support multiple inheritance, How could be achieved?
本文介绍了Swift 不支持多重继承,如何实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码:
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?
}
产生编译时错误:
Address.swift:38:24:来自类City"和Town"的多重继承
Address.swift:38:24: Multiple inheritance from classes 'City' and 'Town'
我怎样才能解决他的那种问题?遵循什么方法?
How can I solve his kind of problem? What approach to follow?
推荐答案
看来你想多了.而不是继承,尝试使用更多的组合.地址不应从 City
继承.为什么?因为从逻辑上讲,地址不是一种城市.相反,城市定义是地址的一部分:
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?
}
这篇关于Swift 不支持多重继承,如何实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文