如何检查任意类型的变量是否为数组?

时间:2022-01-27 16:26:11

I tried to cast a swift protocol array as any array, but failed.

我试图将一个swift协议数组转换成任何数组,但是失败了。

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
}

edit:

编辑:

Inspired by Rohit Parsana's answer, below code could work:

受到Rohit Parsana回答的启发,下面的代码可以工作:

if let arrayType = value?.dynamicType{
    let typeStr = "\(arrayType)"
    if typeStr.contains("Array"){
         print(typeStr)
    }
}

But these code seems not safe enough, for example, you can declare a class named "abcArray".

但是这些代码似乎不够安全,例如,您可以声明一个名为“abcArray”的类。

Although we could use regular expression to check if "typeStr" matches "Array<*>", it seems too tricky.

虽然我们可以使用正则表达式来检查“typeStr”是否匹配“Array<*>”,但这似乎太棘手了。

Is there any better solution?

有更好的解决办法吗?

2 个解决方案

#1


1  

You can use reflection:

您可以使用反射:

if value != nil {
    let mirror = Mirror(reflecting: value!)
    let isArray = (mirror.displayStyle == .Collection)
    if isArray {
        print("type check succeeded")
    }
}

#2


0  

You can check the type of value using 'dynamicType', here is the sample code...

您可以使用“dynamicType”检查值的类型,这里是示例代码……

if "__NSCFArray" == "\(page.dynamicType)" || "__NSArrayM" == "\(page.dynamicType)"
    {
        print("This is array")
    }
    else
    {
        print("This is not array")
    }

#1


1  

You can use reflection:

您可以使用反射:

if value != nil {
    let mirror = Mirror(reflecting: value!)
    let isArray = (mirror.displayStyle == .Collection)
    if isArray {
        print("type check succeeded")
    }
}

#2


0  

You can check the type of value using 'dynamicType', here is the sample code...

您可以使用“dynamicType”检查值的类型,这里是示例代码……

if "__NSCFArray" == "\(page.dynamicType)" || "__NSArrayM" == "\(page.dynamicType)"
    {
        print("This is array")
    }
    else
    {
        print("This is not array")
    }