Game Development Reference
In-Depth Information
Protocols in Swift are used to define the contract of properties and methods that classes,
enumerations, or structures guarantee to implement when extending a protocol. Swift pro-
tocols are very much like Objective-C protocols, but with a little different syntax and a lot
more flexibility. They basic syntax of a protocol is simple.
protocol EngineProtocol {
var type : String {get set}
func start()
func stop()
}
Here you have a protocol named EngineProtocol that defines two functions, start
and stop , and one property type. Take note of the {get set} following the definition
of the type property. This part of the property requirement indicates that any imple-
menter of this protocol must provide a getter and a setter for this property. Let's take a
look at a class that implements this protocol:
class GasPowerEngine : EngineProtocol {
var type : String = "gas"
func start() {
println("I am starting.")
}
func stop() {
println("I am stopping.")
}
}
This class satisfies all the requirements of the protocol and can now be used just like any
other class. You may wonder how you satisfied the property requirement of {get set} .
By default a property has both a getter and a setter. If a class implements this protocol and
implements only a getter, like the following, it will not compile:
class GasPowerEngine : EngineProtocol {
var type : String {
return "gas"
}
func start() {
println("I am starting.")
}
Search WWH ::




Custom Search