我有一个名为 Controller 的类,它包含一个 Array 属性。现在,我的类(class)是这样声明的:
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 中对象的真实类型。有办法吗?我必须使用惰性初始化、结构、泛型类型吗?
下面是伪代码的尝试:
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>
}
}
}
最佳答案
正如 Oscar 和 Elijah 所指出的(投他们一票),我只是想在这里说得更详细一点。您需要在定义类时声明泛型 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]
因此,在您的情况下,不是为 init
方法传递 Bool
,而是在初始化时定义泛型的类型。
关于arrays - 初始化类时设置数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123542/