Game Development Reference
In-Depth Information
println(vehicle.info())
Once you have an instance of your class, you can access its properties and invoke its
methods using the dot (
.
) operator. Go back to your
main.swift
file, replace its body
with this snippet, and run it. Notice how the compiler did not complain about the
Ve-
hicle
class not being imported. In Swift, you have to import only frameworks.
Open your
Vehicle.swift
file, change the declaration of
engine
to the following,
and save your changes:
var engine : String
Swift does not like this. You should see an error message saying “Class Vehicle has no
initializers.” Swift requires you to initialize each variable before you can use an instance
of a class. To do this, you use an
init()
method. Take a look at the new
Vehicle
class:
import Foundation
class Vehicle {
var engine : String
var horsePower : Int
init(engine : String, horsePower : Int) {
self.engine = engine
self.horsePower = horsePower
}
func info() -> String {
return "I am \(engine) powered with \(horsePower)
horse power"
}
}
As you can see, you have added an
init()
method that takes two parameters matching
the two properties of the class. Inside the
init()
, you use the keyword
self
with a dot
followed by the property names to set them to their initial values.
self
, like in Objective-
C, refers to the current instance of the class. Another thing to note about an
init()
method is that it is not prepended by the keyword
func
.
To create an instance of your modified class, you have to change how you pass parameters
to the
init()
. The following shows this change: