Swift mutating關鍵字的使用?
在Swift中,包含三種類型(type): structure,enumeration,class
其中structure和enumeration是值類型(value type),class是引用類型(reference type)
但是與Objective-C不同的是,structure和enumeration也可以擁有方法(method),其中方法可以為實例方法(instance method),也可以為類方法(type method),實例方法是和類型的一個實例綁定的。
在swift官方教程中有這樣一句話:
“Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.”
大致意思就是說,雖然結構體和枚舉可以定義自己的方法,但是默認情況下,實例方法中是不可以修改值類型的屬性。
1. 在結構體的實例方法里面修改屬性
struct Persion {
var name = ""
mutating func modify(name:String) {
self.name = name
}
}
2. 在協(xié)議里面, 如何繼承的結構體或枚舉類型,想要改遍屬性值, 必須添加mutating
protocol Persionprotocol {
var name : String {get}
mutating func modify(name:String)
}
struct Persion : Persionprotocol {
var name = ""
mutating func modify(name:String) {
self.name = name
}
}
3. 在枚舉中直接修改self屬性
enum Switch {
case On, Off
mutating func operatorTion() {
switch self {
case .On:
self = .Off
default:
self = .On
}
}
}
var a = Switch.On
a.operatorTion()
print(a)