I have a class called Controller that contains one Array property. Right now, my class is declared like that:
class Controller {
var myArray: [AnyObject]
init(bool: Bool) {
if bool == true {
myArray = [10, 11, 12]
} else {
myArray = ["Yo", "Ya", "Yi"]
}
}
}
The problem that I have with this code is that myArray is still (of course) of type [AnyObject] after my class initialization. Thus, every time I need to get an object out of myArray, I have to cast its type (Int or String) just like this:
let controller = Controller(bool: false)
let str = controller.array[0] as String
I want to be able to write let str = controller.array[0] //str: String without having to cast the real type of the objects inside myArray. Is there a way to do so? Do I have to use lazy init, struct, generic types?
Here is a attempt in pseudo code:
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>
}
}
}