/**
结构体中的mutating方法
值类型(结构体或者枚举)默认方法是不可以修改属性的,也不可以修改self本身
*/
class MyPerson {
var name: String = ""
var age: Int = 0
func set(name: String,age: Int) -> Void {
self.name = name
self.age = age
}
func show() -> Void {
print("name=\(name),age=\(age)")
}
}
var m0 = MyPerson.init()
m0.set(name: "zhangsan",age: 10)
m0.show()
struct MyPerson1 {
var name: String = ""
var age: Int = 0
mutating func set(name: String,age: Int) -> Void {
/**
结构体枚举等值类型的中,这里在普通的实例方法中不允许修改属性
如果 MyPerson1 是class 就没有必要加mutating
*/
self.name = name
self.age = age
}
func show() -> Void {
print("name=\(name),age=\(age)")
}
}
// 这个不可以修改
// let m11 = MyPerson1.init()
// m11.set(name: 1,age: 1)
var m10 = MyPerson1.init()
m10.set(name: "zhangsan",age: 10)
m10.show()
// 枚举里面
enum LightSwitch {
case OFF,LOW,HIGH
mutating func next() {
switch self {
case .OFF:
self = .LOW
case .LOW:
self = .HIGH
case .HIGH:
self = .OFF
default:
self = .OFF
}
}
}
var light = LightSwitch.OFF
// 调用之后,此时此刻 light == .LOW
light.next()
原文链接:https://www.f2er.com/swift/322411.html