Reputation: 1088
I came across a really weird error today. This code is stripped down to the bare minimum, but it should be enough:
class Sprite: SKSpriteNode {
func setup(pos: CGPoint) {}
}
class Enemy: Sprite {
func setup(health: Int) {}
}
The line inside the enemy class causes the error. The weird thing is, I found a couple of fixes, but I have no idea why they fix it.
The first fix: Don't make Sprite inherit a SpriteKit class. Removing it or changing SKSpriteNode to something random like NSEvent fixes the error.
Secondly: Change the parameter type of pos: to a class I defined myself or add more parameters.
And lastly: Change the parameter type of health: to a class I defined myself or add more parameters. Changing the type to String, CGSize or something similar doesn't solve the error.
In my current code, Enemy.setup takes more parameters than just the health, so this isn't really a problem, but I'm very curious what causes the error and why adding more parameters or changing the parent class of Sprite fixes it.
Upvotes: 1
Views: 50
Reputation: 66244
When subclassing an Objective-C object, you can't have two different methods with the same selector name. Both of these methods translate to setup:
. If someone called the setup:
selector on Enemy
, it would be unclear which implementation to use. Objective-C would treat these methods as having the same name, but Swift would treat them differently because of the type differences.
Naming them differently is the simplest solution:
class Sprite: SKSpriteNode {
func configurePosition(pos: CGPoint) {}
}
class Enemy: Sprite {
func configureHealth(health: Int) {}
}
See this question for more explanation and context.
Upvotes: 1