zoukankan      html  css  js  c++  java
  • [Swift]关键字:class与staitc的区别

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(www.zengqiang.org
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/11411080.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    一、static

    1,结构体 struct 和枚举 enum 的静态属性,静态方法使用 static 关键字

     1 struct Account { 
     2     var amount : Double = 0.0                 //账户金额 
     3     var owner : String = ""                   //账户名 
     4  
     5     static var interestRate : Double = 0.668  //利率
     6  
     7     static func interestBy(amount : Double) -> Double {
     8         return interestRate * amount 
     9     }
    10 }

    2,类 Class 的静态属性,静态方法也可以使用 static 关键字

     1 class Account { 
     2     var amount : Double = 0.0                 //账户金额 
     3     var owner : String = ""                   //账户名 
     4  
     5     static var interestRate : Double = 0.668  //利率
     6  
     7     static func interestBy(amount : Double) -> Double {
     8         return interestRate * amount 
     9     }
    10 }

    二、class

    class 关键字专门用在 class 类型的上下文中的,可以用来修饰类方法以及类的计算属性(注意:不能用在存储类属性上)。

     1 class Account {
     2     var amount : Double = 0.0               // 账户金额 
     3     var owner : String = ""                 // 账户名 
     4   
     5     class var staticProp : Double {
     6         return 0.668 
     7     } 
     8  
     9     class func interestBy(amount : Double) -> Double {
    10         return 0.8886 * amount 
    11     }
    12 } 
    13    
    14 //访问类计算属性 
    15 print(Account.staticProp)

    三、static 与 class 的区别

    1. static 可以在类、结构体、或者枚举中使用。而 class 只能在类中使用。
    2. static 可以修饰存储属性,static 修饰的存储属性称为静态变量(常量)。而 class 不能修饰存储属性。
    3. static 修饰的计算属性不能被重写。而 class 修饰的可以被重写。
    4. static 修饰的静态方法不能被重写。而 class 修饰的类方法可以被重写。
    5. class 修饰的计算属性被重写时,可以使用 static 让其变为静态属性。
    6. class 修饰的类方法被重写时,可以使用 static 让方法变为静态方法。
  • 相关阅读:
    Putty远程登录VMware虚拟机Linux(Ubuntu12.04)
    boost库在工作(39)网络UDP异步服务端之九
    UVA 1401 Remember the Word
    Windbg调试命令详解(1)
    数学之路(3)-机器学习(3)-机器学习算法-余弦相似度(1)
    2012-2013年度总结
    重建二叉树---根据前序和中序遍历结果重建二叉树
    Windbg调试命令详解(2)
    时间操作(JavaScript版)—最简单比較两个时间格式数据的大小
    WO+开放平台:API调用开发手记(话费计费接口2.0)
  • 原文地址:https://www.cnblogs.com/strengthen/p/11411080.html
Copyright © 2011-2022 走看看