Can an [AnyObject] array be optionally downcast to a type-specific array?

You’ve got it — it works exactly like your example code:

let strings = ["Hi", "Hello", "Aloha"]
let anyObjects: [AnyObject] = strings

if let downcastStrings = anyObjects as? [String] {
    println("It's a [String]")
}
// console says "It's a [String]"

No idea about performance, but I wouldn’t assume that it will have to iterate through the full array to determine if a downcast is possible.


So I got curious, and ran a quick test with 100,000 simple values in a couple different [AnyObject] configurations, where I’m trying to downcast the array to a [String] vs. downcasting the individual elements:

// var anyObjects: [AnyObject] = [AnyObject]()
// filled with random assortment of Int, String, Double, Bool
Running test with mixed array
downcast array execution time = 0.000522
downcast elements execution time = 0.571749

// var actuallyStrings: [AnyObject] = [AnyObject]()
// filled with String values
Running test with all strings
downcast array execution time = 1.141267
downcast elements execution time = 0.853765

It looks like it’s super fast to dismiss the mixed array as non-downcastable, since it just needs to scan until it finds a non-String element. For an array that it can downcast, it clearly has to crunch through the whole array, and takes much longer, although I’m not sure why it’s not the same speed as looping through the array and manually checking each element.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)