我创建了两个类,StepsCell和WeightCell
import UIKit
class StepsCell {
let name = "Steps"
let count = 2000
}
import UIKit
class WeightCell {
let name = "Weight"
let kiloWeight = 90
}
在我的VC中,我尝试创建一个数组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)
我没有..为什么?我怎样才能创建一个"持有"这些类和我可以索引以获取各种变量(以及稍后添加的函数)。我认为这将是一件非常简单的事情,但我找不到任何答案。有什么想法吗?
答案 0 :(得分:8)
问题是您创建了一个混合类型的数组。因此,编译器不知道cellArray[0]
返回的对象的类型。它推断此对象必须是AnyObject
类型。显然,它有一个名为name
的属性,它返回nil。
解决方案是将其转换为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)
答案 1 :(得分:2)
正如@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)
您的数组正在保存您创建的类的实例,因此您可以使用临时变量来提取这些值或使其更简单,您也可以执行类似这样的操作
((myArray[0]) as StepsCell ).name
由于你有两个类,并且在运行时我们只是喜欢保持动态,你可以添加一个条件运算符来识别你想要使用的对象类型
if let objectIdentification = myArray[0] as? StepsCell {
println("Do operations with steps cell object here")
}else{
println("Do operation with weight cell object here")
}