Game Development Reference
In-Depth Information
var gallonsInTank : Int
init(engine : String, horsePower : Int, mpg : Int,
gallonsInTank : Int) {
self.engine = engine
self.horsePower = horsePower
self.mpg = mpg
self.gallonsInTank = gallonsInTank
}
var distanceTillEmpty : Int {
get {
return self.mpg * self.gallonsInTank
}
set {
gallonsInTank = newValue / self.mpg
}
}
}
The
mpg
and
gallonsInTank
properties are not very exciting; it's the third property
that is interesting. Starting with the bold text, you can see you have a new variable named
distanceTillEmpty
that is of type
Int
. Following the type definition, you see a set
of braces. This is where the getter and setter of the new property are placed.
You start with the getter in this case. Here you are multiplying
mpg
and
gallon-
sInTank
and returning the result. Notice you are not even using the property
dis-
tanceTillEmpty
. This is why it is called a
computed
property. Its value is determined
inside the getter using other properties of the object.
After the getter, you see the setter. In the setter, you are dividing a variable named
newValue
by the property of
mpg
. Where did this variable,
newValue
, come from?
When using a computed property, the value being passed in to the setter is stored in a con-
stant with the implicit name of
newValue
. Also note that the variable
dis-
tanceToEmpty
is not being set. When using a computed property's set, you are not set-
ting the property's value but modifying the properties that will be used to compute its
value when the getter is called.
Before moving on, go ahead and delete both the Car.swift and Vehicle.swift files from
your project.