Eyal
Eyal

Reputation: 10818

Swift - downcast array of arrays won't compile

How can I downcast array of AnyObject arrays to array of String arrays?

i tried the following code:

let v1:[[AnyObject]] = [["hello"]] // v1 type is [[AnyObject]]
let v2 = v1 as! [[String]]         // compile error!

but this code will not compile with an error:

'String' is not identical to 'AnyObject'

if I just try to downcast array of AnyObject to array of String, it works fine:

let v1:[AnyObject] = ["hello"] // v1 type is [AnyObject]
let v2 = v1 as! [String]       // v2 type is [String] as expected

Upvotes: 5

Views: 192

Answers (1)

matt
matt

Reputation: 535230

You've already answered your own question. Do in the first code, to each element of the array, what you're successfully doing in the second code. Like this:

let v2 = v1.map {$0 as! [String]}

Upvotes: 9

Related Questions