I can\'t seem to find it in the docs, and I\'m wondering if it exists in native Swift. For example, I can call a class level function on an NSTimer like so:
you need to define the method in your class
class MyClass
{
class func myString() -> String
{
return "Welcome"
}
}
Now you can access it by using Class Name eg:
MyClass.myString()
this will result as "Welcome".
Yes, you can create class functions like this:
class func someTypeMethod() {
//body
}
Although in Swift, they are called Type methods.
From the official Swift 2.1 Doc:
You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method.
In a struct, you must use static to define a Type method. For classes, you can use either static or class keyword, depending on if you want to allow your method to be overridden by a subclass or not.
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"
}
}