The following code works:
nil as! String?
"muffin" as! String?
Therefore I also expect this to work:
var magicArray: [Any?] = ["Muffin", nil, 3]
class Box<T> {
var index: Int
init(index: Int){
self.index = index
}
func get() -> T {
return magicArray[index] as! T //crash
}
}
But neither
let box = Box<String?>(index: 0)
box.get()
nor
let box = Box<String?>(index: 1)
box.get()
works as expected. The program crashes at the cast in get()
. This however works:
let box = Box<Int>(index: 2)
box.get()
I need to be able to cast a Any?
value to T
inside my class where T
can be any type, including optionals. The Any?
actually comes from an array of Any?
so there is no other way of verifying it’s of the correct type T
.
Is this possible?