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

Swift中的static func和class func有什么区别?,第1张

概述我可以在Swift库中看到这些定义: extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool}protocol BooleanLiteralConvertible { typealias BooleanLiteralType 我可以在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 @R_419_5135@ (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() //myOtherClassx = MyClass()x.dynamicType.myFunc() //myClass
总结

以上是内存溢出为你收集整理的Swift中的static func和class func有什么区别?全部内容,希望文章能够帮你解决Swift中的static func和class func有什么区别?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1063557.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存