// 报错示例
var stepSize = 1
func increment(_ number: inout Int) {
number = stepSize + number
}
increment(&stepSize)
// 修改方法1
var stepSize = 1
var size = stepSize
func increment(_ number: inout Int) {
number = size + number
}
increment(&stepSize)
// 修改方法2
var stepSize = 1
func increment(_ number: inout Int) {
number = number + number
}
increment(&stepSize)
方法里self的访问冲突
func change(a: inout Int, b: inout Int){
let sum = a + b
a = sum/2
b = sum - a
}
struct Player {
var name: String
var health: Int
var energy: Int
static let maxHealth = 10
mutating func restoreHealth() {
self.health = Player.maxHealth
}
}
extension Player {
mutating func shareHealth(player: inout Player) {
change(a: &health, b: &player.health)
}
}
var a = Player(name: "小明", health: 10, energy: 10)
var b = Player(name: "小红", health: 3, energy: 5)
a.shareHealth(player: &b)
print("a.health = \(a.health) b.health = \(b.health)")
a.shareHealth(player: &a)//报错
func change(a: inout Int, b: inout Int){
let sum = a + b
a = sum/2
b = sum - a
}
struct Player {
var name: String
var health: Int
var energy: Int
static let maxHealth = 10
mutating func restoreHealth() {
self.health = Player.maxHealth
}
}
extension Player {
mutating func shareHealth(player: inout Player) {
change(a: &health, b: &player.health)
}
}
//以下报错
//var a = Player(name: "小明", health: 10, energy: 10)
//change(a: &a.health, b: &a.energy)
//以下不报错
func test() {
var a = Player(name: "小明", health: 10, energy: 10)
change(a: &a.health, b: &a.energy)
}