Reputation: 16149
I saw the code blow from swift 2.0 init
method, Square is a subclass from NamedShape
,
1. do i need to add a self.property
or just use without self
?
2. Does it means properties before super.init(name: name)
use self
, and after not?
class Square : NamedShape {
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4 //Add self. or not
}
}
and
init(sideLengt: Double, name: String) {
sideLength = sideLengt //without self. , is it right?
super.init(name: name)
self.numberOfSides = 4
}
Upvotes: 1
Views: 1020
Reputation: 1204
You can use without self, but the field variable need be different than outside variable.
Simple, variables in field is constant statement (let
) init(sideLength: Double, name: String)
sideLenght
and name
in this line are constants variables, because this you can't set new value for it.
ps. let
in swift is same than const
in other language
Ex.
The correct way to implement is with self.
, because in this case we tell to compiler to set the variable outside in our class.
Other example now setting variable without self.
, look next image, we can use without self because it is outside variable.
Upvotes: 2
Reputation: 2458
you use the keyword self.name
when you are referring to the name
is outside of the init. it's more to recognise what name
you are referring to if you use the same argument "name" as your init parameter
here is an example
var name : String
init(name : String)//here we have the same name with the value above
{
self.name = name//self.name is the variable outside of the init and now we are making that value the same with the value used in init
}
Upvotes: 1