2

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.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
hippo_san
  • 360
  • 2
  • 12

1 Answers1

2

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:

enter image description here

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).

Droppy
  • 9,691
  • 1
  • 20
  • 27
  • This works, thank you. But I still do not understand why they declare agent as GKAgent in Swift, but GKAgent2D in Objective-C.. – hippo_san Jun 17 '15 at 08:03
  • Oh yeah, it is both `GKAgent`, my bad. The demo code just change it to `- (void)agentDidUpdate:(nonnull GKAgent2D *)agent` when implementing. – hippo_san Jun 17 '15 at 08:36