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. :)
To declare a constant, you use the let keyword. Take a look at the following example in which we declare street as a constant instead of a variable. If we only update the first line, replacing var with let , Xcode throws an error for obvious reasons. Trying to change the value of a constant is not allowed in Swift.
However there is another data type in Swift called Optional, whose default value is a null value ( nil ). You can use optional when you want a variable or constant contain no value in it.
You write a failable initializer by placing a question mark after the init keyword ( init? ). Note: You cannot define a failable and a nonfailable initializer with the same parameter types and names. A failable initializer creates an optional value of the type it initializes.
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name.
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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With