我可以在Swift库中看到这些定义:
extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool } protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self }
定义为static func的成员函数和定义为func类的另一个函数之间有什么区别?是简单的静态是结构和枚举的静态函数,类和协议的类?有什么其他差别,应该知道吗?在语法本身中有这种区别的理由是什么?
这是主要区别。一些其他的区别是类函数是动态分派的,可以被子类覆盖。
原文链接:https://www.f2er.com/swift/321755.html协议使用类关键字,但它不排除结构体实现协议,他们只是使用静态。为协议选择了类,因此不必有第三个关键字来表示静态或类。
来自Chris Lattner关于这个主题:
We considered unifying the Syntax (e.g. using “type” as the keyword),but that doesn’t actually simply things. The keywords “class” and “static” are good for familiarity and are quite descriptive (once you understand how + methods work),and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose “class”),but on balance it is the right tradeoff.
class MyClass{ class func myFunc(){ println("myClass") } } class MyOtherClass: MyClass{ override class func myFunc(){ println("myOtherClass") } } var x: MyClass = MyOtherClass() x.dynamicType.myFunc() //myOtherClass x = MyClass() x.dynamicType.myFunc() //myClass