Swift检查值是否为数组(任何类型) [英] Swift check if value is of type array (of any type)
问题描述
如果值是一个数组,我该如何检查Swift?问题在于 Int
类型的数组显然不能被转换为 Any
类型的数组。假设我有一个 myArray
类型的 Int
数组并执行以下操作:
如果让array = myArray as? [任何] {返回true}
它不会返回true(实际上令我感到意外)。字典出现同样的情况。我想要一个字符串,任何
(意味着 Any
可以是任何类型)的字典。我该如何检查它是否是?
预先感谢。 解决方案
协议数组类型{} $ b我们可以像这样工作,但它并不像我希望的那样美丽: $ b扩展Array:ArrayType {}
let intArray:Any = [1,2,3]
let stringArray:Any = [hi,hello,world]
intArray是ArrayType // true
stringArray是ArrayType // true
编辑:我想我之前误解了你的问题,现在我明白了:
let intArray = [1,2 ,3]
let anyArray = intArray.map {$ 0 as Any}
这是我了解的唯一途径。
How can I check in Swift if a value is an Array. The problem is that an array of type Int
can apparently not be casted to an array of type Any
. Suppose I have an array myArray
of type Int
and execute the following:
if let array = myArray as? [Any] { return true }
it doesn't return true (which surprises me actually). The same thing appears with dictionaries. I want a dictionary of type String, Any
(meaning that Any
can be any type). How can I check if it is?
Thanks in advance.
Got it working like this, although it's not as beautiful as I would've hoped:
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
EDIT: I think I misunderstood your question before, now I got it though:
let intArray = [1, 2, 3]
let anyArray = intArray.map{ $0 as Any }
This is the only way to my knowledge.
这篇关于Swift检查值是否为数组(任何类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!