Game Development Reference
In-Depth Information
override func info() -> String {
return "\(super.info()) and I am at
(\(latitude),\(longitude))"
}
}
As you look over these changes, you will see that you modify
init()
to include the two
new properties, and you add a new method with the keyword
override
prepended to
the method declaration.
override
tells the compiler you want to replace the parent
method with this one. To see the new
Car
in action, go back to Xcode, create a new Swift
file named
Car.swift
, and copy this code into its body. After you have done this, go
back to
main.swift
, add the following lines, and rerun the program:
var car = Car(engine: "gas",
horsePower: 500,
latitude: "39.7392 N",
longitude: "104.9847 W")
println(car.info())
When you run the program this time, you will see the output from the new
info()
meth-
od.
I am gas powered with 500 horse power and I am at (39.7392
N,104.9847 W)
Computed Properties
You have already seen Swift's simple properties, but it also has the ability to use explicit
getters and setters for more complex operations. To see how you can use computed prop-
erties, let's go back to the original
Vehicle
class and add two new properties,
mpg
and
gallonsInTank
, and a getter and setter for a third property,
dis-
tanceTillEmpty()
. Here are the changes:
import Foundation
class Vehicle {
var engine : String
var horsePower : Int
var mpg : Int