Assigning to constant in Swift initializer

4.3k views Asked by At

In my Ball.swift file, I declared the following variable:

let r:Double = 0

Now I have the following initializer:

init(x:Double, y:Double, radius:Double) {
    self.r = radius
}

I am getting the following error:

Cannot assign to 'r' in 'self'

However, in Apple's Swift docs here, they say:

You can assign a value to a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.

I don't understand. Shouldn't this work? I have searched a lot online but can't find anything. I was thinking about just making it a variable, but I feel like that would be giving up. :)

4

There are 4 answers

0
ABakerSmith On BEST ANSWER

You need to declare r with no initial value, like so:

let r: Double

As of Swift 1.2, a constant can only be assigned once. If you give it a default value you cannot give it another value in init.

0
Icaro On

As per the documentation you cited in your post you have to always initialize the superclass before be able to use self in your class.

From what class your class inherited from? Lets suppose it inherited from, in this case your initializer would be a convenience initializer, convenient initializers can just call the local initializers, so your code would look like this:

convenience init(x:Double, y:Double, radius:Double) {
    self.init()
    self.r = radius
}

If in other hand you are inheriting from a class that has a similar initializer you would override it and call the super initializer, like this:

override init(x:Double, y:Double, radius:Double) {
    super.init(x, y, radius)
    self.r = radius
}
0
Wingzero On

you are giving let r:Double = 0 at first, and you change it in init functions. This is not the way it works.

For example:

let r : Double
init(x:Double, y:Double, radius:Double) {
    self.r = radius
}

init() {
    self.r = 0
}
0
Bannings On

You can assign a value to a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes. Once a constant property is assigned a value, it can’t be further modified.

You can define a constant property without assigned a value

let r:Double // = 0

then you can:

init(x:Double, y:Double, radius:Double) {
    self.r = radius
}