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.

  • UIImage not displaying using Swift
  • swift tableview displays json data very slow
  • Int is not convertible to Dictionary<string, string>
  • How to use UnsafeMutableRawPointer to fill an array?
  • how to block user , if he/she not connected to internet connection when my app load
  • Mapping a JSON object to a Swift class/struct
  • 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


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

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

    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 Solutions Collect From Internet About “How to check if an variable of any type is an array”

    You can use reflection:

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

    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")
            print("This is not array")