简体   繁体   中英

Determine Swift Array Type

I'm trying to determine the type of a collection using Swift. That is my goal. It does not appear to be supported by the new language so I tried to fall back on Objective-C. Collection generics is a new feature and I believe was only added for Swift interoperability.

Is anyone aware of a feature that will allow me to inspect the array type of d ?

class SuperClass : NSObject { }

class SubClass: SuperClass { }

let a = SubClass()

if a.isKindOfClass(SuperClass) {
// this works as expected like objective-c
    print("yes") 
}

let b = Array<SubClass>()
if b.isKindOfClass(Array<SuperClass>)  { 
// error: value type of 'Array<SubClass>' has no member isKindOfClass
    print("yes")
}

if b is Array<SuperClass> {
// error: 'SuperClass' is not a subtype of 'SubClass'
    print("yes")
}

You can simply test it with Array<String>() is Array<String> but If you wanna know which type have any variable you can look at d.dynamicType

@crashmstr is right

In your case b is an Array literal (a value type), not a reference type. So it can't call isKindOfClass .

try this

if let array = b as? Array<SuperClass>
{
    //perform some action
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM