在阅读Swift文档的“内存安全性”部分后,我想到了一个我无法回答的问题。
因此,我有以下代码,这些代码是基于Swift文档的摘要:
func balance(_ x: inout Int, _ y: inout Int) {
let sum = x + y
x = sum / 2
y = sum - x
}
struct Player {
var name: String
var health: Int
var energy: Int
}
// 1 - Memory Safety test for two different integers (just to see how this works)
var playerOneScore = 42
var playerTwoScore = 30
balance(&playerOneScore, &playerTwoScore)
print("Player 1 Balanced Score is: \(playerOneScore)")
print("Player 2 Balanced Score is: \(playerTwoScore)")
// 2 - Memory Safety test for the same two integers. COMPILE-TIME ERROR HERE.
balance(&playerOneScore, &playerOneScore)
print("Player 1 Balanced Score is: \(playerOneScore)")
print("Player 2 Balanced Score is: \(playerTwoScore)")
// 3 - Memory Safety test for the same property of a struct instance. THIS WORKS FINE.
var holly = Player(name: "Holly", health: 14, energy: 10)
balance(&holly.health, &holly.health)
print("Holly's Balanced Health is \(holly.health)")
// 4 - Memory Safety test for the same property of a tuple. THIS ALSO WORKS FINE.
var playerInformation = (health: 10, energy: 20)
balance(&playerInformation.health, &playerInformation.health)
print("Health is: \(playerInformation.health)")
print("Energy is: \(playerInformation.energy)")
因此,从文档中,我理解了此代码第2节中的错误,因为我将两次在内存中写入相同的位置。 问题出现在第3节和第4节。看来我应该得到与第2节相同的错误,因为在两种情况下,我还将访问内存中的相同地址。我在这里想念什么?
此外,文档说与我的代码中第4节中的代码相似的代码应产生错误。来自文档的原始代码如下:
var playerInformation = (health: 10, energy: 20)
balance(&playerInformation.health, &playerInformation.energy)
// Error: conflicting access to properties of playerInformation
最后,我的代码的第3节应该产生一个错误,根据Apple的说法,解决该错误的方法是将其设置为局部变量。来自文档的原始代码如下:
var holly = Player(name: "Holly", health: 10, energy: 10)
balance(&holly.health, &holly.energy) // Error
func someFunction() {
var oscar = Player(name: "Oscar", health: 10, energy: 10)
balance(&oscar.health, &oscar.energy) // OK
}
因此,总而言之,问题是:
A)为什么我的代码中的第2部分有效而第3和4部分无效?
B)为什么苹果公司文档中的代码片段中的错误实际上并没有在编译器中产生错误并且可以正常工作?
谢谢!