壮志,敢教日月换新天。为有牺牲多

[Swift]关键字:class与staitc的区别

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

一、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 让方法变为静态方法。
posted @   为敢技术  阅读(640)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示