I have the following implementation of some GKStates
import GameplayKit.GKState
class Running: GKState {
let validNextStates: [GKState.Type] = [Paused.self, Over.self]
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return self.validNextStates.contains(where: { stateClass is $0 })
}
}
class Paused: GKState {}
class Over: GKState {}
Does anyone have a hint on why I get Expected type after 'is'
at $0
? validNextStates
is defined as an array of GKState Types so why is one of it's elements not recognised as a Type?
Edit:
Xcode: Version 12.1 (12A7403)
The problem is the type of stateClass
. stateClass
is of type AnyClass
, which is just a typealias for AnyObject.Type
and hence stateClass
is a meta-type, not a normal type, so the is
operator cannot be used on it.
However, to compare meta types, you can use the equality operator.
class Running: GKState {
let validNextStates: [GKState.Type] = [Paused.self, Over.self]
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return self.validNextStates.contains(where: { $0 == stateClass })
}
}
class Paused: GKState {}
class Over: GKState {}
class Invalid: GKState {}
Running().isValidNextState(Paused.self) // true
Running().isValidNextState(Invalid.self) // false