Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - downcast array of arrays won't compile

Tags:

casting

ios

swift

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
like image 870
Eyal Avatar asked Sep 03 '15 14:09

Eyal


1 Answers

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]}
like image 103
matt Avatar answered Oct 14 '22 12:10

matt