我有一个名为Controller的类,它包含一个数组属性。现在,我的课是这样宣布的:
class Controller {
var myArray: [AnyObject]
init(bool: Bool) {
if bool == true {
myArray = [10, 11, 12]
} else {
myArray = ["Yo", "Ya", "Yi"]
}
}
}
我在这段代码中遇到的问题是,myArray在类初始化之后(当然)仍然是[AnyObject]类型。因此,每次我需要从myArray中获取对象时,我都必须像这样转换它的类型(Int或String):
let controller = Controller(bool: false)
let str = controller.array[0] as String
我希望能够编写
let str = controller.array[0] //str: String
而不必在myArray中强制转换对象的真实类型。有办法吗?我必须使用lazy init、struct和泛型类型吗?下面是对伪代码的尝试:
class Controller {
var myArray: Array<T> //Error: use of undeclared type 'T'
init(bool: Bool) {
if bool == true {
myArray = [10, 11, 12] as [Int] //myArray: Array<Int>
} else {
myArray = ["Yo", "Ya", "Yi"] as [String] //myArray: Array<String>
}
}
}
最佳答案
正如奥斯卡和以利亚指出的那样(向他们投票),我只是想在这里说得更详细一些。定义类时,需要声明泛型T
。
这意味着您需要在初始化类时定义泛型的类型。
class Foo<T> {
var items = [T]()
}
let stringFoo = Foo<String>()
stringFoo.items.append("bar")
stringFoo.items[0] = "barbar"
stringFoo.items // ["barbar"]
let intFoo = Foo<Int>()
intFoo.items.append(1)
intFoo.items[0] = 11
intFoo.items // [11]
所以在您的例子中,与其为
Bool
方法传递init
,不如在初始化时定义泛型的类型。关于arrays - 初始化类时设置数组的类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25123542/