Swift: Index out of bounds error, I'm so confused

I can’t understand why this "Index out of bounds" error is occuring.
I want to know what’s the difference between "Index out of bounds" and "Index out of range" and why my code is causing error. Thank you.

Code

var input = readLine()!.split(separator: " ").map{Int($0)!}
var arr = input[1...20]

for (i, a) in arr.enumerated() {
    print(i, a)
}
print(arr[0]) // Index out of bounds 

Input

1 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

Output

0 900
1 901
2 902
3 903
4 904
5 905
6 906
7 907
8 908
9 909
10 910
11 911
12 912
13 913
14 914
15 915
16 916
17 917
18 918
19 919
Swift/SliceBuffer.swift:287: Fatal error: Index out of bounds
2023-05-04 15:01:32.280783+0900 SwiftAlgorithm[86091:6733992] Swift/SliceBuffer.swift:287: Fatal error: Index out of bounds
Program ended with exit code: 9

>Solution :

It’s because the array slice isn’t copying the elements and creating a new array, but it creates a “pointer” to the initial one instead, so the indices don’t apply here the same way they would for a new array. This is implemented this way for the benefit of memory efficiency. This is really well described in the Apple developer documentation, as well as how the indices are being kept from the initial array.

Leave a Reply