0

How can I check if a property is an Array (of any type)? This code always only prints "Worker". Is there a way (dynamically) to know if a property is an Array without inform the type?

final class Worker: NSObject {

    var id: Int?
    var array: Array<Worker>?

}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let worker = Worker()
        worker.id = Int(2) as Int?
        worker.array = [Worker(),Worker(),Worker()]

        let mirror = reflect(worker)

        for i in 0..<mirror.count {

            let (name, childMirror) = mirror[i]

            if childMirror.disposition == .Optional {

                let (newName,subChildMirror) = childMirror[0]

                if subChildMirror.valueType is Array<AnyClass>.Type {
                    println("AnyClass")
                }
                if subChildMirror.valueType is Array<AnyObject>.Type {
                    println("AnyObject")
                }
                if subChildMirror.valueType is Array<Any>.Type {
                    println("Any")
                }
                if subChildMirror.valueType is Array<NSObject>.Type {
                    println("NSObject")
                }
                if subChildMirror.valueType is Array<Worker>.Type {
                    println("Worker")
                }

            }

        }

    }
}

Ps.: I need to deal with Array<>

Klevison
  • 3,342
  • 2
  • 19
  • 32
  • possible duplicate of [Swift Pattern match on Array](http://stackoverflow.com/questions/32156910/swift-pattern-match-on-arrayany) – Dániel Nagy Sep 17 '15 at 19:09

1 Answers1

0

An array of any type can always be casted to a NSArray. So you could check if it's an array with code like this:

if _ = subChildMirror.valueType as? NSArray {
      println("Array")
}

It's also possible to dynamically get the type of the objects of that array. In my EVReflection library I do something similar. I extended the Array in order to get a new element of an object what should be in that Array. In your case you could then get the .dynamicType from dat object.

So the code would become:

let arrayType = worker.array.getTypeInstance().dynamicType

Here is the Array extension

extension Array {
    /**
    Get the type of the object where this array is for

    :returns: The object type
    */
    public func getTypeInstance<T>(
        ) -> T {
            let nsobjectype : NSObject.Type = T.self as! NSObject.Type
            let nsobject: NSObject = nsobjectype.init()
            return nsobject as! T
    }
}
Edwin Vermeer
  • 13,017
  • 2
  • 34
  • 58