[英]How to loop through array of classes with different types and print their properties in swift?
I am learning to work with classes and now I need to loop through array of classes with different types and print their properties. 我正在学习使用类,现在我需要循环使用不同类型的类数组并打印它们的属性。
It was not a problem, when there was only one super class and few subclasses, but problem occurred, when I added another superclass and it's subclasses. 这不是问题,当只有一个超类和几个子类时,但是当我添加另一个超类和它的子类时出现了问题。 xCode told me to cast my array as [Any] and I lost my ability to rich class properties.
xCode告诉我将我的数组转换为[Any],我失去了丰富的类属性的能力。
let human = People(name: "John Dou", height: 180, weight: 80, gender: "male") //every class inherits from class People this way
var peopleArray = [human, cook, manager, fighter] // this is an array of classes with type People
for person in peopleArray {
print(person.name, person.height, person.weight, person.gender)
person.say()
}
This for in loop works fine. 这对in循环工作正常。
Then I created few classes, which inherits from class Marsian: 然后我创建了几个继承自Marsian类的类:
let marsian = Marsian(numberOfLegs: 1, planetOfBirth: "Mars")
Then I tried to put instances of every class in an array: 然后我尝试将每个类的实例放在一个数组中:
let unitedRaceArray = [marsian, snikersian, twixian, austronaut, fighter, manager, cook, human]
But it shawed me an error: "Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional" 但它给我一个错误:“异构集合文字只能推断为'[Any]';如果这是有意的话,添加显式类型注释”
Of course, with type [Any], "for in" loop doesn't work. 当然,对于[Any]类型,“for in”循环不起作用。
Write 写
let unitedRaceArray: [People]
and you should be fine. 你应该没事 If you want to access Martian's write
如果你想访问Martian的写作
if let martian = person as? Martian {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.