This code:
let d0 = Data(bytes: [10, 11, 12, 13, 14, 15])
print(d0[2])
print(d0[3])
let d1 = d0[2...3]
print(d1.count)
print(d1[0])...produces this output in an Xcode 9.3 / Swift 4.1 playground:
12
13
2...and then crashes on the last line:
print(d1[0])...with this error:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
Is this a bug, and if so, any suggestions for a workaround?
if you test :
print(d1[2], d1[3])you get
12 13
So, that shows that indexes still refer to the original array.
It is normal behavior for slices, as documented here :
h ttps://developer.apple.com/documentation/swift/arrayslice
Unlike
Array and ContiguousArray, the starting index for an ArraySlice instance isn’t always zero. Slices maintain the same indices of the larger array for the same elements, so the starting index of a slice depends on how it was created, letting you perform index-based operations on either a full array or a slice.