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

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] = stringsif 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, BoolRunning test with mixed arraydowncast array execution time = 0.000522downcast elements execution time = 0.571749// var actuallyStrings: [AnyObject] = [AnyObject]()// filled with String valuesRunning test with all stringsdowncast array execution time = 1.141267downcast 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.


Let's try this

var someObjects = [    NSString(),    NSUUID()]let uuids = someObjects as? NSUUID[]

uuids is nil

var someOtherObjects = [    NSUUID(),    NSUUID()]let all_uuids = someOtherObjects as? NSUUID[]

all_uuids is equal to someOtherObjects

So it looks like it does work. You can use the expression to test if all elements of the array are of the expected type but it will not filter the array to select only the expected type.