如何检查任何类型的变量是否为数组 [英] How to check if an variable of any type is an array
问题描述
我尝试将快速协议数组转换为任何数组,但是失败。
I tried to cast a swift protocol array as any array, but failed.
protocol SomeProtocol: class{
}
class SomeClass: NSObject, SomeProtocol{
}
let protocolArray: [SomeProtocol] = [SomeClass()]
let value: Any? = protocolArray
if let _ = value as? [SomeProtocol]{
print("type check successed") //could enter this line
}
以上代码可以按预期工作。
但是,我的问题是,我有很多协议,我不想一一检查。添加新协议是不友好的。
Above code could work as expected. However, my problem is, I have a lot of protocols, and I don't want to check them one by one. It is not friendly to add new protocol.
是否有任何方便的方法来检查值上方是否是下面的数组?
Is there any convenience way to do check if above "value" is a kind of array like below?
if let _ = value as? [Any]{
print("type check successed") //never enter here
}
编辑:
受Rohit Parsana的回答启发,以下代码可以工作:
Inspired by Rohit Parsana's answer, below code could work:
if let arrayType = value?.dynamicType{
let typeStr = "\(arrayType)"
if typeStr.contains("Array"){
print(typeStr)
}
}
但是这些代码似乎不够安全,例如,您可以声明一个名为 abcArray的类。
But these code seems not safe enough, for example, you can declare a class named "abcArray".
尽管我们可以使用正则表达式来检查 typeStr是否与 Array< *>,似乎太棘手了。
Although we could use regular expression to check if "typeStr" matches "Array<*>", it seems too tricky.
有没有更好的解决方案?
Is there any better solution?
推荐答案
您可以使用反射:
if value != nil {
let mirror = Mirror(reflecting: value!)
let isArray = (mirror.displayStyle == .Collection)
if isArray {
print("type check succeeded")
}
}
这篇关于如何检查任何类型的变量是否为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!