Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
let prices = [10, 20, 30]
let item = prices[prices.count]
print(item)The program crashes
- Expecting
30: takingcountfor the index of the last element. Indices start at zero, so the last one iscount - 1, and indexcountcrashes the program. - Expecting
nil: reading by an index gives a plainInt, not an optional likefirstandlast. An index that does not exist stops the program withIndex out of range.
- How do you read the last element of
priceswithout going past the bounds? - What does
prices.last ?? 0print, and why does it never crash?