Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Fatal error: Index out of range (out of bounds index)

Tags:

ios

swift

iphone

Hello I am trying to learn swift. I have a little experience with javascript so i tried modeling this loop in the same manner i usually do. The function actually outputs what its supposed to but I keep getting an error message and I am unsure of what I am doing wrong. Here is my code:

import UIKit
let dir: [String] = ["north", "east", "south", "west"]
var num = dir.count
func move(){
    for i in 0 ... num{
        var holder = dir[i]
        switch holder{
        case "north":
            print("you've moved north")
        case "east":
            print("you've moved east")
        case "south":
            print("you've moved south")
        case "west":
            print("you've moved west")
        default:
            print("where you going?")
        }
        if i == 3{
            print("round the world")
        }

    }
}

move()

i get this error on the last line "move()"

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

this is what outputs to the console:

you've moved north

you've moved east

you've moved south

you've moved west

round the world

Fatal error: Index out of range: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444

like image 541
sallycakes Avatar asked Sep 18 '25 02:09

sallycakes


1 Answers

In your code trying to access 4th index due to you have used ... in loop control syntax. And 4th index not in array.

Here is some details about for swift loop.

for index in 0...4 {
 ...
}

The above snippet says, iterate over the range starting at 0 and inclusive of 4 i.e from 0–4

If you do not want 4 included, you use this called the half-open range operator (..<).

for index in 0..<4 {
 ...
}

This would loop from 0 to 3 and stop execution.

like image 131
Mitesh Avatar answered Sep 19 '25 17:09

Mitesh