Search code examples
arraysswift2introspection

Swift 2 - Check Type of empty Array (Introspection)


I'm currently working on introspection in Swift 2 and have Problems getting the specific type for an Array (in this example an Array<String>).

var prop = obj.valueForKey("strings")!

if prop is Array<String> {
println("true")
}
if prop is Array<Int> {
println("true")
}

Output is:

true
true

while it should be

true
false

Is there a way to find out the type for the members of the Array? For example, if I daclared the Array as Array<String> I want to get String or at least be able to check if it is. MirrorType also did not lead to any success on that by now.


Solution

  • There are 2 ways to achieve what you want:

    1. if prop.dynamicType == Array<Int>.self (or [Int].self) which is better than if prop.dynamicType == [Int]().dynamicType { because [Int]() creates an unused instance of "array of integers".
    2. Typically, when you check if an array is specific-typed, you plan to use it in a certain way (as a result, you will likely cast your array to [Int]). Having that said, I recommend using if let arrayOfInts = prop as? Array<Int> {. Using this construct, you will check for type compatibility and prepare your array to be treated in a special way (using the casted arrayOfInts reference).

    Anyway, it's up to you to decide what to do.