这两者之间有什么区别?
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)
}
}
}
答案 0 :(得分:6)
class func
是一种类方法。通过向班级发送消息来调用它。
func
是一种实例方法。通过向类的实例发送消息来调用它。
答案 1 :(得分:3)
实例方法。
class Counter {
var count = 0
func increment() {
++count
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
用法:
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
输入方法:
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
用法:
SomeClass.someTypeMethod()
答案 2 :(得分:2)
不同之处在于你调用这样的类函数:
UIFont.PrintFontFamily("test")
但是'构建'只有func关键字的函数需要创建类的实例并在该实例上调用方法:
var myFont = UIFont()
myFont.PrintFontFamily("test")
答案 3 :(得分:1)
使用类:
调用类函数let font = UIFont(name: "Helvetica Neue", size: 30)
font.PrintFontFamily("Helvetica Neue")
非类函数是从实例化对象调用的方法:
{{1}}
在这种情况下,您应该使用类func
答案 4 :(得分:0)
在类型本身上调用class func
,而在该类型的实例上调用func
。
一个例子:
class Test {
func test() {
}
}
致电test()
:
Test().test()
class func
class Test {
class func test() {
}
}
致电test()
:
Test.test()
所以,你不必做一个班级的实例。
您也可以拨打static func
。 static func
和class func
之间的区别在于static func
转换为class final func
,这意味着子类无法覆盖该函数。