swift之mutating关键字

原文:http://blog.csdn.net/tounaobun/article/details/39694233?utm_source=tuicool&utm_medium=referral

swift中,包含三种类型(type): structure,enumeration,class

其中structure和enumeration是值类型(value type),class是引用类型(reference type)

但是与objective-c不同的是,structure和enumeration也可以拥有方法(method),其中方法可以为实例方法(instance method),也可以为类方法(type method),实例方法是和类型的一个实例绑定的。

在swift官方教程中有这样一句话:

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. “Structures and enumerations are value types. By default, the properties of a value type  
  2.  cannot be modified from within its instance methods.”  
  3.   
  4. 摘录来自: Apple Inc. “The Swift Programming Language”。 iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329  

大致意思就是说,虽然结构体和枚举可以定义自己的方法,但是默认情况下,实例方法中是不可以修改值类型的属性。


举个简单的例子,假如定义一个点结构体,该结构体有一个修改点位置的实例方法:

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. struct Point {  
  2.     var x = 0, y = 0  
  3.       
  4.     func moveXBy(x:Int,yBy y:Int) {  
  5.         self.x += x  
  6.         // Cannot invoke '+=' with an argument list of type '(Int, Int)'  
  7.         self.y += y  
  8.         // Cannot invoke '+=' with an argument list of type '(Int, Int)'  
  9.     }  
  10. }  

编译器抛出错误,说明确实不能在实例方法中修改属性值。

为了能够在实例方法中修改属性值,可以在方法定义前添加关键字mutating

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. struct Point {  
  2.     var x = 0, y = 0  
  3.       
  4.     mutating func moveXBy(x:Int,yBy y:Int) {  
  5.         self.x += x  
  6.         self.y += y  
  7.     }  
  8. }  
  9.   
  10. var p = Point(x: 5, y: 5)  
  11.   
  12. p.moveXBy(3, yBy: 3)  


另外,在值类型的实例方法中,也可以直接修改self属性值。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. enum TriStateSwitch {  
  2.     case Off, Low, High  
  3.     mutating func next() {  
  4.         switch self {  
  5.         case Off:  
  6.             self = Low  
  7.         case Low:  
  8.             self = High  
  9.         case High:  
  10.             self = Off  
  11.         }  
  12.     }  
  13. }  
  14. var ovenLight = TriStateSwitch.Low  
  15. ovenLight.next()  
  16. // ovenLight is now equal to .High  
  17. ovenLight.next()  
  18. // ovenLight is now equal to .Off”  

TriStateSwitch枚举定义了一个三个状态的开关,在next实例方法中动态改变self属性的值。


当然,在引用类型中(即class)中的方法默认情况下就可以修改属性值,不存在以上问题。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值