Reputation: 39181
Whats the difference between these 2?
extension UIFont {
class func PrintFontFamily(font: FontName) {
let arr = UIFont.fontNamesForFamilyName(font.rawValue)
for name in arr {
println(name)
}
}
}
extension UIFont {
func PrintFontFamily(font: FontName) {
let arr = UIFont.fontNamesForFamilyName(font.rawValue)
for name in arr {
println(name)
}
}
}
Upvotes: 1
Views: 1515
Reputation: 2147
A class func
is called on the type itself, while just func
is called on the instance of that type.
An example:
class Test {
func test() {
}
}
To call test()
:
Test().test()
Here is the same thing with a class func
class Test {
class func test() {
}
}
To call test()
:
Test.test()
So, you don't have to make an instance of the class.
You can also call a static func
. The difference between a static func
and a class func
is that static func
translates into class final func
which just means that subclasses cannot override the function.
Upvotes: 1
Reputation: 1927
Instance method.
class Counter {
var count = 0
func increment() {
++count
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
Usage:
let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.incrementBy(5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0
Type methods:
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
Usage:
SomeClass.someTypeMethod()
Upvotes: 3
Reputation: 25459
The difference is that you call an class function like this:
UIFont.PrintFontFamily("test")
But 'constructing' the function with just the func keyword require create instance of the class and call the method on that instance:
var myFont = UIFont()
myFont.PrintFontFamily("test")
Upvotes: 3
Reputation: 1542
A class function is called with the class :
UIFont.PrintFontFamily("Helvetica Neue")
A non class function is a method you call from an instantiated object :
let font = UIFont(name: "Helvetica Neue", size: 30)
font.PrintFontFamily("Helvetica Neue")
In that case, you should use a class func
Upvotes: 1
Reputation: 534885
A class func
is a class method. It is called by sending a message to the class.
A func
is an instance method. It is called by sending a message to an instance of the class.
Upvotes: 6