sveinhal
(Svein Halvor Halvorsen)
21
Opinion presented as fact.
CTMacUser
(Daryle Walker)
22
That can only be done by not making copies in the first place.
- Make the array a stored instance property of a class type.
- Don't let any code touch that property, besides instance-level methods.
- Within those methods, if the array is mutated, it must occur before any copies of the array are made. Further, those copies should neither be mutated nor escape the method. (Hopefully, you shouldn't make any copies at all.)
To mutate the elements and record which to remove, manually loop over the indices! Use the upcoming API that handles discontiguous indexes. Right now, you can download the preview from Apple's GItHub.
/// Removes the reference to `x` on the remote collection, and returns whether `x` needs to be purged from the local collection.
func doSomething(_ x: inout MyAwesomeType) -> Bool { /*...*/ }
class Example {
typealias ArrayType = [MyAwesomeType]
var array: ArrayType
// More properties...
init() {
array = Array()
//...
}
func checkAndRemove() {
var deadIndices = RangeSet<ArrayType.Index>(), i = array.startIndex
let end = array.endIndex
while i < end {
defer { array.formIndex(after: &i) }
let doRemove = doSomething(&array[i])
if doRemove {
deadIndices.insert(i, within: array)
}
}
array.removeSubranges(deadIndices)
}
}
dabrahams
(Dave Abrahams)
23
I would strongly advise against using this technique as a way to improve performance; it is certainly not required in the code shown
To mutate the elements and record which to remove, manually loop over the indices!
Likewise, I wouldn't do this. The advice is supposedly geared at avoiding a loop over the array's indices, but that's not problematic for arrays, as their Indices are just just Range<Int>.