mardi 23 août 2016

Check if an object is an instance of class meta type in Swift

I have an array of objects of various types and an array of types. For each object, I'd like to iterate over the array of types and see if the object is that type. Something like this:

class Parent {}
class ChildA: Parent {}
class ChildB: Parent {}
class GrandChildA: ChildA {}

var objects: [Any] = ["foo", ChildA(), ChildA(), ChildB(), GrandChildA()]
var classes = [Parent, ChildA, ChildB] // This line doesn't compile!!

for obj in objects {
    for cls in classes {
        if obj is cls {
            NSLog("obj matches type!")
        }
    }
}

This doesn't work because you can't store classes in an array. As I understand, you can store class types such as ChildA.self:

ChildA().dynamicType == ChildA.self // true

But this doesn't handle subclasses:

ChildA().dynamicType == Parent.self // false

Obviously the is operator solves the subclass case:

ChildA() is Parent // true

But if I want to use is, I don't know how to store the class types in an array.

Can I accomplish what I want somehow using Swift and some reflection voodoo?

Sorry if the title is misleading -- I don't understand this well enough to form a proper question.





Aucun commentaire:

Enregistrer un commentaire