I have a list of arrays look like this:
var lists = [[Category]]()
Each element in the "lists" represents an array of object (Category), I’m trying to reinit the "lists" (clear every element) after using it.
My approach:
lists.forEach { list in
list.removeAll()
}
Error: Can not mutate the "list" because "list" is a constant variable
Is there anyway I can achieve my goal in Swift?
5
Answers
You can assign an empty array literal which is written as [ ] (an empty pair of square brackets)
lists is now an empty array, but still of type
[[Category]]
Since arrays are value types and they have copy-on-write semantics, "clearing all the nested arrays of an array" is indistinguishable from "creating a new array with as many empty nested arrays as there are nested arrays in the old array, and reassigning it to the old array".
So you can do
Alternatively:
From the comments, it seems like you are writing a function that clears all the nested arrays. In that case, you need an
inout
parameter:And to call it:
If you really want your function to mutate an arbitrary number of lists that you pass in, you’d need to use unsafe pointers (very not recommended):
And
clearList(&listCate1, &listCate2)
would actually changelistCate1
andlistCate2
, but this is a rather dirty trick.You can remove all the element of an array and keep the capacity.
or if you want to remove object from array based on some conditions then you can use this…
I’d create an extension with mutable and immutable variants. By extending
RangeReplaceableCollection
rather thanArray
we don’t need to constrainArray.Element
to any specific type.Now we can strip in place if our array is declared mutable:
Or we can use the immutable variant for
let
constants: