1

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.

Cristik
  • 30,989
  • 25
  • 91
  • 127
CommaToast
  • 11,370
  • 7
  • 54
  • 69

1 Answers1

2

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]
Cristik
  • 30,989
  • 25
  • 91
  • 127
  • Does not work. That was the first thing I tried... will post you the error message when I am back at the computer. .. Maybe it's because I'm in the Playground? – CommaToast Jan 23 '16 at 22:27
  • Turns out you were right. The problem was that I was trying to use Array as the key type. Doesn't work. But when I used NSArray as the key type, it works. So: `let myDictionary: [NSArray:AnyClass] = ["route","to","class":customGKState.self]` etc. etc. it works fine. It also helps if the class that you are referring to (like foobar.self) is ABOVE where you are in the code. – CommaToast Jan 24 '16 at 06:36