22

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...

mfaani
  • 33,269
  • 19
  • 164
  • 293
Drakalex
  • 1,488
  • 3
  • 19
  • 39

1 Answers1

28

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

Community
  • 1
  • 1
Daniel Galasko
  • 23,617
  • 8
  • 77
  • 97
  • 2
    I already saw this post but after reading it again I understood thanks, my bad – Drakalex Dec 17 '14 at 18:32
  • But how to set a optional argument for the intialization. This answered the intent of the question but not what anyone else is looking for with that questions title. – Chrissi Grilus Jul 29 '21 at 10:05