Reputation: 3
I am taking an online class on swift and an example was shown. Why is self used with the init method call but not on colour?
class Car {
var colour = "Black"
var numberOfSeats = 5
var typeOfCar : CarType = .Coupe
init() {
}
convenience init (customerChosenColour : String) {
self.init()
colour = customerChosenColour
}
}
Upvotes: 0
Views: 89
Reputation: 7718
As you wonder why self.
cannot be omitted in self.init()
, you can think of self.init()
as whole is a special keyword just for convenience initializer. Same as super.init()
as whole is a special keyword just for designated initializer. And Car.init()
aka Car()
is for creating a new instance. Calling init()
itself without any receiver is not a valid call ever. So you can treat function call init()
as nonexistence, self.init()
is one keyword, super.init()
is another keyword.
init()
is not a member function, it is the initializer, some special code which will be run when creating new instances of that class. Don't treat initializers as regular member functions. They don't have the func
keyword in front. They don't have the property of member functions. You can call member function on an instance but you cannot call initializer on an instance (Car().init()
is not valid). self.init()
dose NOT mean calling a function named init()
from self
.
class Foo
{
init(){}
func foo(){}
func bar()
{
self.foo() //valid. regular member function call
self.init() //invalid. init() is not a member function of the instance
}
}
Don't think self.init()
like calling regular method from the same class, where self.
can be omitted, but rather treat the whole thing as a special keyword that means "initialize this object with the designated initializer first".
Upvotes: 0
Reputation:
An init()
runs when someone makes a new instance of that class like this:
var newInstanceOfCar = Car()
A convenience init
allows you to create other initializers for certain use cases, like when there is a customerChosenColour
that needs to be specified. It makes things more convenient in those cases.
The reason why self
is used, is because when you create convenience init
, you still need to call the "main" init
, which is a property of self
.
You can use self
on colour, but it isn't necessary. You would use self.colour
, if colour
was ambiguous, like in this example:
class Car {
var colour = "Black"
var numberOfSeats = 5
var typeOfCar : CarType = .Coupe
init() {
}
convenience init (colour : String) {
self.init()
self.colour = colour
}
}
Notice how colour
is a property of Car
, but is also the name of the parameter for the convenience init
. It would be confusing to write colour = colour
.
So we use self
to say that we want the variable in our class, self.colour
, to be equal to the value of the parameter, colour
.
Upvotes: 1