我怎样才能在Swift中创build一个类的数组

我创build了两个类,StepsCell和WeightCell

import UIKit class StepsCell { let name = "Steps" let count = 2000 } import UIKit class WeightCell { let name = "Weight" let kiloWeight = 90 } 

在我的VC我试图创build一个数组,cellArray,以保存对象。

 import UIKit class TableViewController: UIViewController { var stepsCell = StepsCell() var weightCell = WeightCell() override func viewDidLoad() { super.viewDidLoad() var cellArray = [stepsCell, weightCell] println(StepsCell().name) println(stepsCell.name) println(cellArray[0].name) } 

但是当我索引到数组中时:

 println(cellArray[0].name) 

我得到零。为什么? 我怎样才能创build一个“拥有”这些类的数组,我可以索引到获取各种variables(和函数稍后添加)。 我认为这将是一个超级简单的事情,但我找不到任何答案。 有任何想法吗?

问题是你创build一个混合types的数组。 因此,编译器不知道cellArray[0]返回的对象的types。 它推断这个对象必须是AnyObjecttypes的。 显然这有一个名为name的属性,返回nil。

解决scheme是要么将其转换为println((cellArray[0] as StepsCell).name) ,要么使用公共协议或超类:

 protocol Nameable { var name: String { get } } class StepsCell: Nameable { let name = "Steps" let count = 2000 } class WeightCell: Nameable { let name = "Weight" let kiloWeight = 90 } var stepsCell = StepsCell() var weightCell = WeightCell() var cellArray: [Nameable] = [stepsCell, weightCell] println(StepsCell().name) println(stepsCell.name) println(cellArray[0].name) 

正如@Rengers在他的回答中所说的,你可以使用这个方法,深入到你的代码中,你可以像这样解决它,

 class StepsCell { let name = "Steps" let cellCount = 2000 } class WeightCell { let name = "Weight" let weightCount = 90 } var stepcell = StepsCell() // creating the object var weightcell = WeightCell() // Your array where you store both the object var myArray = [stepcell,weightcell]; // creating a temp object for StepsCell let tempStepCell = myArray[0] as StepsCell println(tempStepCell.name) 

你的数组是持有你创build的类的实例,所以你可以使用一个临时variables来提取这些值或使其更简单,你也可以做这样的事情

 ((myArray[0]) as StepsCell ).name 

既然你有两个类,在运行的时候,我们只是喜欢保持dynamic,你可以添加一个条件运算符来识别你想要的对象的types

 if let objectIdentification = myArray[0] as? StepsCell { println("Do operations with steps cell object here") }else{ println("Do operation with weight cell object here") }