How do I declare a class level function in Swift?
Yes, you can create class functions like this:
class func someTypeMethod() {
//body
}
Although in Swift, they are called Type methods.
You can define Type methods inside your class with:
class Foo {
class func Bar() -> String {
return "Bar"
}
}
Then access them from the class Name, i.e:
Foo.Bar()
In Swift 2.0 you can use the static
keyword which will prevent subclasses from overriding the method. class
will allow subclasses to override.
UPDATED: Thanks to @Logan
With Xcode 6 beta 5 you should use static
keyword for structs and class
keyword for classes:
class Foo {
class func Bar() -> String {
return "Bar"
}
}
struct Foo2 {
static func Bar2() -> String {
return "Bar2"
}
}