Game Development Reference
In-Depth Information
func stop() {
println("I am stopping.")
}
}
So far you have seen only instance methods defined in your protocols. If you want to add
a class method, also known as a static , requirement to a protocol, you simply prefix the
function definition with the keyword class . Here is a short example doing just this:
protocol TypeProtocol {
class func type() -> String
}
class MyClass: TypeProtocol {
class func type() -> String {
return "MyClass"
}
}
println("The class type is \(MyClass.type())")
Extensions
Extensions in Swift allow you to add functionality to an existing class, structure, or enu-
meration. They are much like Objective-C categories but do not have names, which makes
for a much more readable syntax.
The syntax of a Swift protocol is straightforward and looks like a Swift class or structure,
but using the keyword extension as opposed to class or structure . To see how
they work, let's create an extension to the String class that adds a reverse function.
extension String {
func reverse() -> String {
var s = ""
for char in self {
s = String(char) + s
}
return s
}
}
Search WWH ::




Custom Search