Swift中的static func和class func有什么区别?

我可以在Swift库中看到这些定义:
extension Bool : BooleanLiteralConvertible {
    static func convertFromBooleanLiteral(value: Bool) -> Bool
}

protocol BooleanLiteralConvertible {
    typealias BooleanLiteralType
    class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self
}

定义为static func的成员函数和定义为func类的另一个函数之间有什么区别?是简单的静态是结构和枚举的静态函数,类和协议的类?有什么其他差别,应该知道吗?在语法本身中有这种区别的理由是什么?

这是主要区别。一些其他的区别是类函数是动态分派的,可以被子类覆盖。

协议使用类关键字,但它不排除结构体实现协议,他们只是使用静态。为协议选择了类,因此不必有第三个关键字来表示静态或类。

来自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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...