2

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
}

edit:

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

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".

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

Is there any better solution?

2 Answers 2

1

You can use reflection:

if value != nil {
    let mirror = Mirror(reflecting: value!)
    let isArray = (mirror.displayStyle == .Collection)
    if isArray {
        print("type check succeeded")
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's awesome! Thanks!
0

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

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

1 Comment

I am afraid it does not work. "__NSCFArray", "__NSArrayM" seems like an objc array, and I am using swift here. The dynamic type of "value" is actually "Array<SomeProtocol>"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.