Yan Peng Yan Peng - 1 year ago 71
Swift Question

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


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?

Answer Source

You can use reflection:

if value != nil {
    let mirror = Mirror(reflecting: value!)
    let isArray = (mirror.displayStyle == .Collection)
    if isArray {
        print("type check succeeded")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download