简体   繁体   English

如何循环使用不同类型的类数组并在swift中打印它们的属性?

[英]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.

相关问题 如何在Swift中遍历不同类的所有属性? - How iterate through all properties of different classes in Swift? 如果使用不同类型的元素,如何在循环中打印数组中的每个元素? - How to print every element in array in loop if with different types of element? 不同类型的 Swift 数组 - Swift array of different types Swift - 如何循环遍历此数组并打印每个值而不会出现下标错误 - Swift - How do I loop through this array and print each value without subscript error 如何循环遍历从不同索引开始的数组,同时仍然快速遍历整个数组? - How to loop through arrays starting at different index while still looping through entire array in swift? 如何遍历类并在数组中添加文本 - How to loop through classes and add text in array 如何遍历具有不同属性的100个对象的数组并从每个对象中检索1个属性值? - How to loop through an array of 100 objects with different properties and retrieve 1 property value from each? 如何遍历数组的元素<UnsafeMutablePointer>在斯威夫特 - how to loop through elements of array of <UnsafeMutablePointer> in Swift 如何在 Swift 中使用 for 循环遍历元组数组 - How to iterate through a tuple array with for loop in Swift 如何在swift中循环遍历一个对象数组 - How to loop through an array of objects in swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM