Reputation: 145
What exactly does it mean for a function to be defined this way:
class Foo {
private class func bar() {
//do something cool
}
}
In other words, what is the purpose of the second class
keyword here?
Using Swift 2.1.
Upvotes: 3
Views: 703
Reputation: 25966
class
and static
methods are invoked via the type, rather than on instances.
let x = NSString.pathWithComponents(["/", "usr", "local", "bin", "brew"])
Any type can have static
methods, class
methods may only occur on classes. Subclasses can override class
methods but not static
ones.
class Foo {
class func bar() -> String {
return "foo bar"
}
static func baz() -> String {
return "foo baz"
}
}
class Bar: Foo {
override class func bar() -> String {
return "bar bar"
}
}
Upvotes: 6
Reputation: 19839
It simply declares the function on the class itself rather than an instance of the class.
class Foo {
private class func omg() -> String {
return "OMG"
}
}
Foo.omg() => "OMG"
calling
let f = Foo()
f.omg() => Static member 'omg' cannot be used on instance of type 'Foo'
So you can see the difference
Upvotes: 3
Reputation: 960
it is a class function, so you can call it on a class, no class instances. it is the same as static in java/c++
class A {
public class func f() {
print("hey")
}
}
A.f()
Upvotes: 1