0

In the example below is stateClass: AnyClassan actual instance of a class that for example I could then call to get stateClass.name or is it simply a reference to the class type. My feeling is that from the validChange line that its just a reference to Class Type not an actual instance of any class that I can pull data out of?

override func isValidNextState(stateClass: AnyClass) -> Bool {
    let validChange = stateClass is MonsterAttack.Type
    return validChange
}
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

3 Answers3

2

AnyClass is defined as followed: typealias AnyClass = AnyObject.Type which is the actual class type itself. So if you have a class with name "Test" you have to pass Test.self and you can only call static/class methods/properties and initializers on it. If you want to use the actual instance use AnyObject (only for classes) or Any(for anything):

override func isValidNextState(stateClass: AnyObject) -> Bool {
    let validChange = stateClass is MonsterAttack.Type
    return validChange
}
Qbyte
  • 12,753
  • 4
  • 41
  • 57
  • If you want to access the instance of that class you can do `stateMachine!.stateForClass(stateClass)` – Sez Sep 12 '15 at 02:14
  • @sez What type has `stateMachine`? – Qbyte Sep 12 '15 at 10:48
  • It's a `GKStateMachine`. Note that it will return `nil` if the state has been constructed but not added to a state machine yet. But since `isValidNextState` is called by the state machine that owns that state it should be fine to call `stateForClass` inside `isValidNextState`. – Sez Sep 13 '15 at 23:46
1

It is simply a reference to the class type, ie you could call:

isValidNextState(SomeClass.self)
Logan
  • 52,262
  • 20
  • 99
  • 128
1

Classes are reference types. So when you pass stateClass, you're simply passing the pointer to the stateClass instance of MonsterAttack. So stateClass is an instance yes, but it is the same instance to the one that you passed into your isValidNextState function

The let validChange appears be just optionally casting the argument into a MonsterAttack type.

This answer may help further: https://stackoverflow.com/a/27366050/4396258

Community
  • 1
  • 1
Mark
  • 12,359
  • 5
  • 21
  • 37