Game Development Reference
In-Depth Information
var vehicle = Vehicle(engine: "gas", horsePower: 500)
The first thing to take note of is you are not explicitly calling init() . This is because
when you create a class using its name, it implicitly calls the matching init() . Another
thing to look at is you are now using labels when passing values to a method. This is a re-
quirement of Swift. When you are invoking a method on an object that contains a para-
meter list, you must label the values being passed. As you saw earlier, this is not required
when calling functions.
Extending Classes
To extend a class in Swift, you follow the class name with a colon ( : ) and the name of the
class you are extending. The following class defines a new class named Car that extends
the original Vehicle :
import Foundation
class Car : Vehicle {
init(engine : String, horsePower : Int) {
super.init(engine : engine, horsePower : horsePower)
}
}
Notice the init() method. It has the same parameter list as its parent, and it calls its
parent, passing the required values to ensure the parent is properly initialized. Before you
run the code again, let's add some functionality to the new class.
The car has an upgrade and includes a navigation system and therefore will have two new
properties, lat and long , that represent the location of the car. Let's add these properties
now. Here is the new Car :
class Car : Vehicle {
var latitude : String
var longitude : String
init(engine: String, horsePower : Int, latitude:
String, longitude: String) {
self.latitude = latitude
self.longitude = longitude
super.init(engine : engine, horsePower : horsePower)
}
Search WWH ::




Custom Search