Kwangle
Kwangle

Reputation: 349

Adding New Parameters to a Child Class in Swift

I've been writing a game that has a subclass of the SKSpriteNode with some extra functions and variables. I'd like to set some of the variables when the object is created eg

let mySprite = MySubclass (width: 24, height 33)

I'm not sure this is possible which means I'll probably have to call a methos of the subclass to set the vars in a separate stage which is a bit clunky:

let mySprite = MySubclass ()
mySprite.setSize(24, height: 33)

Any ideas how I can do this in a more elegant way?

Many Thanks, Kw

Upvotes: 0

Views: 133

Answers (1)

Grimxn
Grimxn

Reputation: 22507

This is very fundamental OOP. Here is how you do it in Swift:

class MySubClass: SKSpriteNode {
    var width: CGFloat       // Declare your own properties
    var height: CGFloat      // ...

    init(width: CGFloat, height: CGFloat) {
        self.width = width   // set up your own properties
        self.height = height // ...
        super.init()         // call up to the super-class's init to set up its properties 
    }
}

Have you read Apple's book The Swift Programming Language? It's free and clearly covers this...

Upvotes: 2

Related Questions