Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter in class initialization

Tags:

I'm working with Swift, Sprite-Kit and Xcode 6,

I have a class declared like this :

class Obstacles: SKSpriteNode
{
    init(initTime: Int, speed: CGFloat, positionX: CGFloat, rotationSpeed: CGFloat)
    {
        self.initTime = initTime
        self.rotationSpeed = rotationSpeed
        self.positionX = positionX

        super.init(texture: SKTexture(imageNamed: "Rectangle"), color: SKColor.redColor(), size: CGSize(width: 20, height: 20))
        self.speed = speed
    }

    var initTime: Int
    var positionX: CGFloat
    var rotationSpeed: CGFloat = 0
}

So I can assign a variable to this class like this :

var myVariable = Obstacles(initTime: 100, speed: 3.0, positionX: 10.0, rotationSpeed: 0.0)

but if for example I don't want to initialize the rotationSpeed value and have it default to 0.0, how can I manage to do so ? I can't remove the parameter, it results me an error...

like image 957
Drakalex Avatar asked Dec 17 '14 17:12

Drakalex


People also ask

How do you make a class parameter optional in Python?

A Python optional argument is a type of argument with a default value. You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement.

How do you pass optional parameters in constructor?

You can use a question mark to define optional parameters in a class constructor function. Alternatively, you can set a default value for the parameter, which will be used if a value is not provided when instantiating the class.

What is an optional parameter in a function?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.


1 Answers

What you want is to set a default value for rotationSpeed but you are forgetting to declare the type and assign a default value. Instead of saying rotationSpeed: 0.0) you would have rotationSpeed: CGFloat = 0. Making your initializer look like this:

init(initTime: Int, speed: CGFloat, positionX: CGFloat, rotationSpeed: CGFloat = 0)

You also might find this SO post useful as well

like image 59
Daniel Galasko Avatar answered Sep 19 '22 13:09

Daniel Galasko