类func与仅func之间的区别

时间:2015-07-15 15:17:44

标签: ios swift function

这两者之间有什么区别?

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)
        }
    }
}

5 个答案:

答案 0 :(得分:6)

class func是一种类方法。通过向班级发送消息来调用它。

func是一种实例方法。通过向类的实例发送消息来调用它。

答案 1 :(得分:3)

"Instance methods are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the keyword static 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."

实例方法。

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 funcstatic funcclass func之间的区别在于static func转换为class final func,这意味着子类无法覆盖该函数。

相关问题