Swift convenience initializer extension for SKPhysicsBody

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 19:43:59

As @Cristik guessed in the comments, this is the same root problem as this question and this question: the public SKPhysicsBody class is a convenience interface for the private PKPhysicsBody class that provides its implementation.

In the past, this approach relied heavily on the "duck typing" behavior of Objective-C — as long as ClassA responds to all the same selectors as ClassB, you can call any of those selectors on a pointer whose static type (the type declared to the compiler in source code) is ClassB, even if the actual object at run time is really an instance of ClassA.

Swift is stricter about runtime type correctness than ObjC, so "duck typing" alone is not enough. Since iOS 9 / OS X 10.11, SpriteKit has some workarounds that allow PKPhysicsBody instances to better pretend to be SKPhysicsBody instances.

But those don't cover all cases — in particular, it doesn't catch (ObjC) [SKPhysicsBody alloc] returning a PKPhysicsBody instance, which means any attempt to add initializers to SKPhysicsBody in Swift will fail. (Because the ObjC alloc/init process is reduced to one initializer call in Swift.)

I'd consider this a bug and recommend filing it with Apple.


Edit/update: And until that bug gets fixed (it's been a year and some now), the workaround is to make your convenience "initializer" into a class method instead. (Or a global function if you must, but... ewww.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!