In GameplayKit, I want to conform the protocol GKAgentDelegate, hence use the delegate method func agentDidUpdate(agent: GKAgent)
.
The problem is, in this method, the parameter agent is declared as GKAgent, not GKAgent2D, so that I cannot access agent.position
, because the position property is in GKAgent2D, not GKAgent...
However in Objective-C API, agent is declared as GKAgent2D.
Please help.
As GKAgent2D
is a subclass of GKAgent
, you can simply upcast it:
func agentDidUpdate(agent: GKAgent) {
if let agent2d = agent as? GKAgent2D {
// do thing with agent2d.position
}
}
The documentation for GKAgentDelegate
(from Xcode 7, beta 1; i.e. the OSX 10.11 SDK) shows the same type (GKAgent
) for both languages:
So it should have always been GKAgent
under Objective-C in order to be strictly correct, however Objective-C is less type-safe than Swift, so you could get away with it (with the possibility that you'd get an unrecognized selector
exception if a GKAgent
object was ever passed to the delegate method and you assumed it was a GKAgent2D
).