Referring to the official tutorial, there is memory conflict in swift, however, based on the knowledge of my javascript, there is not a memory conflict, the code below will always be right.
func balance(_ x: inout Int, _ y: inout Int) {
let sum = x + y
x = sum / 2
y = sum - x
}
var playerOneScore = 42
var playerTwoScore = 30
balance(&playerOneScore, &playerTwoScore) // OK
balance(&playerOneScore, &playerOneScore) // Error: conflicting accesses to playerOneScore
From Memory Safety:
And later:
Therefore, passing the the same variable as in-out parameter to
counts as overlapping write accesses to the same memory location, and therefore as a conflict.
For the rationale and more details, see SE-0176 Enforce Exclusive Access to Memory, which has been implemented in Swift 4. In particular, exclusive memory access is enforced to
As an example, the following two seemingly equivalent functions are in fact not equivalent if the same variable is passed as an inout argument, so that mutating
xcan affectyand vice versa:Another example:
If mutating
xmight modifyyand vice versa, the compiler cannot optimize the code to load the value ofyin a register first, i.e. perform the equivalent ofIt has also been discussed (see Eliminating non-instantaneous accesses?) to eliminate long-term access by making temporary copies for the duration of the function call which are assigned back when the function returns, i.e. do something like
This idea was discarded because it is bad for the performance, even for “simple types” but much worse for “container types” like
Array.