I decided to subclass SKSpriteNode
for a game test in Swift today and soon realised that it was not as simple as my Objective-C background suggested. After a little hunting around and a bit of testing in Playgrounds I have come up with the following (See below). I have not tested this in a project as I am just starting out on my next game but thought I would add this here to see if I am on the right track with this, does what I have done look right, any suggestions or comments would be most helpful.
I am pretty happy with this, but I was just curious if there was anything I was not doing, or something that I was doing that I should not be.
// ------------------------------------------------------------------- **
// SKSpriteNode subclass, NSCoding not implemented
// ------------------------------------------------------------------- **
class SimpleSprite: SKSpriteNode {
var simpleName: String
var simpleType: Double
init(simpleName: String, simpleType: Double) {
self.simpleName = simpleName
self.simpleType = simpleType
let spriteColor = SKColor.redColor()
let spriteSize = CGSize(width: 10.0, height: 10.0)
super.init(texture: nil, color: spriteColor, size: spriteSize)
}
required init?(coder aDecoder: NSCoder) {
// Class does not want to be NSCoding-compatible
fatalError("init(coder:) has not been implemented")
}
}
let simpleSprite = SimpleSprite(simpleName: "SimpleRabbit", simpleType: 22.1)
simpleSprite.simpleName
simpleSprite.color
// ------------------------------------------------------------------- **
// SKSpriteNode subclass, NSCoding-compatible
// ------------------------------------------------------------------- **
class CodedSprite: SKSpriteNode {
var simpleName: String
var simpleType: Double
init(simpleName: String, simpleType: Double) {
self.simpleName = simpleName
self.simpleType = simpleType
let spriteColor = SKColor.whiteColor()
let spriteSize = CGSize(width: 10.0, height: 10.0)
super.init(texture: nil, color: spriteColor, size: spriteSize)
}
required init?(coder aDecoder: NSCoder) {
self.simpleName = aDecoder.decodeObjectForKey("SIMPLE_NAME") as String
self.simpleType = aDecoder.decodeDoubleForKey("SIMPLE_TYPE")
super.init(coder: aDecoder)
}
override func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.simpleName, forKey: "SIMPLE_NAME")
aCoder.encodeDouble(self.simpleType, forKey: "SIMPLE_TYPE")
super.encodeWithCoder(aCoder)
}
}
let codedSprite = CodedSprite(simpleName: "CodedRabbit", simpleType: 22.1)
codedSprite.simpleName
codedSprite.color