One case where the difference matters is when you have a collection-of-collections. To avoid confusion, let’s say an Array
of Data
:
var x = [Data(repeating: 10, count: 2),
Data(repeating: 11, count: 3)]
// Element-mutating version:
x.modifyAll{ data in
data[0] = 15
}
// Element-replacing version
x.updateAll{ data in
var newData = data
newData[1] = 14
return newData
}
print(x.map{Array($0)})
Even if the compiler is smart enough to produce equivalent code for the two implementations (can we get confirmation of that?) there still remains a massive readability difference at the call-site.
Although…I just stumbled on a weird case where the compiler requires type annotation (and has an unhelpful diagnostic):
var z = [[2, 2], [3, 3, 3]]
z.modifyAll{ array in
array.modifyAll{ n in // error: passing value of type 'Int' to an inout parameter requires explicit '&'
n += 10
}
}
The actual fix is to replace “n in
” with “(n: inout Int) in
”, OR to replace “n += 10
” with “n = n + 10
”. And I don’t understand why.