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.
There are 2 ways to achieve what you want:
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".[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.