如果值是数组,如何在 Swift 中检查。问题是 type 的数组Int显然不能转换为 type 的数组Any。假设我有一个myArray类型数组Int并执行以下命令:
if let array = myArray as? [Any] { return true }
Run Code Online (Sandbox Code Playgroud)
它不会返回 true (这实际上让我感到惊讶)。字典也出现同样的情况。我想要一个类型的字典String, Any(意味着Any可以是任何类型)。我怎样才能检查它是否是?
提前致谢。
让它像这样工作,尽管它并不像我希望的那么漂亮:
protocol ArrayType {}
extension Array : ArrayType {}
let intArray : Any = [1, 2, 3]
let stringArray : Any = ["hi", "hello", "world"]
intArray is ArrayType // true
stringArray is ArrayType // true
Run Code Online (Sandbox Code Playgroud)
编辑:我想我之前误解了你的问题,现在我明白了:
let intArray = [1, 2, 3]
let anyArray = intArray.map{ $0 as Any }
Run Code Online (Sandbox Code Playgroud)
这是我所知的唯一途径。
| 归档时间: |
|
| 查看次数: |
8943 次 |
| 最近记录: |