Game Development Reference
In-Depth Information
If you run the new code, you will see 11 printed to the console.
Classes
Classes in Swift are the main ingredients of most applications. They are reusable pieces of
code that encapsulate both state and functionality. The components of a class are its meth-
ods and properties. When speaking in relation to classes, we refer to functions as methods
and variables as properties . The basic syntax of a class follows:
class MyClass {
// insert class definition here
}
While this class does not do anything, it is a complete class. This is one of the really nice
features of Swift. Unlike Objective-C, you don't need an interface file ( .h ). In Swift, the
interface and implementation are in a single file, and the external interface is automatic-
ally made available to all other consumers. Let's see some examples.
Go back to your Xcode project, create a new Swift file named Vehicle.swift , copy
the following code into it, and save the file:
import Foundation
class Vehicle {
var engine : String = "gas"
var horsePower : Int = 500
func info() -> String {
return "I am a \(engine) powered vehicle with
\(horsePower) horse power"
}
}
Here you have defined a simple class named Vehicle that has two properties, engine
and horsepower , and a single method named info() . To create a class, you invoke its
default initializer by referencing the class's name followed by an empty set of paren-
theses.
var vehicle = Vehicle()
println("engine type : \(vehicle.engine)")
println("horse power : \(vehicle.horsePower)")
Search WWH ::




Custom Search