Search code examples
swiftgamekitgameplay-kit

What is the syntax to store a Class as a value in a Dictionary in Swift?


Lets say I want to do this:

class foobar : NSObject {
//method declarations, etc.
}

Then later:

let myDictionary:Dictionary = ["returnMeAnAwesomeClass":foobar]

Does not work.

If I put in foobar.Type, it also doesn't work.

If I put in foobar.class as foobar.Type, it also doesn't work.

The reason I want this is because there's a method in a system API that takes a class as the argument, e.g.:

func enterState(_ stateClass: AnyClass) -> Bool

(in GKStateMachine)

I'd find it acceptable to be able to get a string and turn that into a class.


Solution

  • You can use foobar.self if you need to obtain the class type. And also you should add type safety to your dictionary:

    let myDictionary: [String:AnyClass] = ["returnMeAnAwesomeClass": foobar.self]
    

    If you're initializing the dictionary at the same place where you're declaring it, you can skip the type declaration, as the compiler will infer it:

    let myDictionary = ["returnMeAnAwesomeClass": foobar.self]