Swift - 向下转换的数组数组将无法编译

时间:2022-09-10 23:23:23

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

如何将AnyObject数组的数组转换为String数组的数组?

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'

'String'与'AnyObject'不同

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

如果我只是尝试将AnyObject的数组向下转换为String数组,它可以正常工作:

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

1 个解决方案

#1


9  

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]}

#1


9  

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]}