I was playing with arrays and its slices. I noticed that the editor doesn't show the error or warning if I'm trying to update/insert an element in the slice. My thinking is that as the slice sliceNames is declared as var its elements should be editable. If it's not editable then IDE/VScode should show an error/warning even before we compile.
Please let me know if I'm missing anything here.
let names = ["Alice", "Bob", "Charlie", "David", "Eve"]
var sliceNames = names[1...3]
// The below statements doesn't show error or warning in the IDE/Editor
sliceNames[0]="Arun"
sliceNames.insert("Arun", at: 0)
let foo = ["p","o","i","n","t"]
var bar = foo[1...3]
// bar = "o","i","n"
bar[3] = "k"
// now, bar = "o","i","k"
// but foo is unchanged.
So, no errors expected. I expect what is happening is that the ArraySlice code does a copy-on-write if you assign to it, and at that point it's no longer a reference to the original array.
Just found in the docs ( Documentation ) that the slices' index doesn't always start at 0. So In my case the editor should warn me even before I compile the code.
In general, there isn’t a way to check whether the value you’ve passed to someArray[someIndex] is within the bounds of the array at compile time without either not being very useful or sometimes falsely reporting that an index could be out of bounds when it definitely won’t be. I imagine that is the main reason that Swift doesn’t try to warn on the sliceNames[0] in your case.
The compiler doesn't have that kind of special knowledge about standard library types. ArraySlice is just a plain old struct with a subscript as far as the compiler is concerned. You can declare a subscript that takes an arbitrary integer value.
Yeah, ArraySlice is an odd beast. I've pretty much decided that doing anything more complicated than for-in iteration or looking at first or last is likely to be a problem. If I want to do something more with that section of an Array, I'll make a new Array copy of the slice.