致命错误:Swift索引超出范围(索引越界)

4

你好,我正在尝试学习Swift。我有一点JavaScript的经验,所以我试图用与平时相同的方式来建立这个循环。实际上函数输出了它应该输出的结果,但我一直收到错误消息,不确定自己做错了什么。以下是我的代码:

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()

我在最后一行 "move()" 上面遇到了这个错误:

错误:执行被中断,原因:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)。

这是控制台输出的内容:

你向北移动

你向东移动

你向南移动

你向西移动

绕过世界

致命错误:索引超出范围:文件 /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift,第444行


num = dir.count 返回 4,因为这是数组中元素的数量。但是你循环从元素零(正确)到元素 4(不存在)。使用 0..<num,就像 Ashish 演示的那样,循环从零到 num 减一。 - Magnas
为了更好地理解,您可以查看Swift官方文档,即https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html - Ashish Langhe
既然您是Swift的新手,这里有一个建议-如果您想要迭代数组而不需要知道索引,请使用“for item in array { ... }”类型的循环。 - sats
4个回答

4

你的代码尝试访问第四个索引,由于你在循环控制语法中使用了"... ",而第四个索引不在数组中。

以下是有关Swift循环的一些详细信息:

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

上面的代码片段表示,迭代从0开始并包括4在内的范围,即从0到4。

如果你不想包括4,你可以使用半开区间运算符(..<)。

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

这将循环从0到3并停止执行。


1
我投票支持这个答案,因为它提供了深入的解释!我完全理解为什么会出错,我认为其他新手也会明白! - sallycakes
2
@sallycakes 正确的方法是 for index in dir.indices { - Leo Dabus

3
在Swift中,有更高效的循环方式...但为了更好地理解您所实现的内容...
我已更新您的代码...它将正常运行。
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()

输出:

you've moved north
you've moved east
you've moved south
you've moved west
round the world

在Swift中愉快地编码 :-)


1
非常感谢你,它确实帮助我理解了语法!我已经将@MiteshPrajapati的答案标记为正确,因为我认为它将更好地帮助像我这样的新手理解为什么会出现这个错误。 - sallycakes

0

所以,这里你首先要计算的是数字 num,它是 4。

enter image description here


0
import UIKit

class ViewController: UIViewController {

    let dir: [String] = ["north", "east", "south", "west"]

    override func viewDidLoad() {
        super.viewDidLoad()
         move()
        // Do any additional setup after loading the view.
    }

    func move(){
        for (index, element) in dir.enumerated() {
       //   print("Item \(index): \(element)")
            switch element{
                        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 index == 3{
                            print("round the world")
                        }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接