加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:18:27 所属栏目:百科 来源:网络整理
导读:我可以在Swift库中看到这些定义: extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) - Bool}protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func convertFromBooleanLiteral(v
我可以在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读