Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - Would mutating an ArraySlice instantiate a new array instance?

var absences = [0, 2, 0, 4, 0, 3, 1, 0]
let midpoint = absences.count / 2

var firstHalf = absences.prefix(upTo: midpoint)
let secondHalf = absences.suffix(from: midpoint)

Quotation from Apple:

Neither the firstHalf nor secondHalf slices allocate any new storage of their own. Instead, each presents a view onto the storage of the absences array.

When I try to mutate firstHalf as the following:

firstHalf[1] = 19

the values of firstHalf changes but the original array absences remains the same (firstHalf[1] is equal to 19 while absences[1] equals to 2) So what happens in the background. Did I instantiate a new array by mutating the array slice? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, the standard library's collection types, including Array and ArraySlice, all have copy-on-write behaviour. This means that they can share storage of their elements with other collections until they are mutated, in which case they will take their own copy of them.

In your case, the underlying array buffer that the slice firstHalf has a view onto is non-uniquely referenced (as both absences & secondHalf also have a view onto it). Therefore when you go to mutate firstHalf, a copy is triggered – creating a new buffer containing the elements of the slice (but not necessarily the entire array).

firstHalf now has a unique view onto this new buffer, with absences & secondHalf both sharing a view onto the old array buffer. Therefore firstHalf can now mutate the elements of its buffer without affecting the elements of the original array, thus preserving value semantics.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...