[英]Swift Fatal error: Index out of range (out of bounds index)
你好,我正在尝试学习 swift。我对 javascript 有一点经验,所以我尝试以与通常相同的方式对这个循环进行建模。 function 实际上输出了它应该输出的内容,但我不断收到一条错误消息,我不确定自己做错了什么。 这是我的代码:
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(代码=EXC_I386_INVOP,子代码=0x0)。
这是输出到控制台的内容:
你已经向北移动
你搬到东部了
你搬到南方了
你搬到了西部
环游世界
致命错误:索引超出范围:文件/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift,第444行
由于您在循环控制语法中使用了...,因此在您的代码中尝试访问第 4 个索引。 第 4 个索引不在数组中。
下面是关于 swift 循环的一些细节。
for index in 0...4 {
...
}
上面的代码片段说,遍历从 0 开始并包含 4 的范围,即从 0–4
如果您不想包含 4,则使用这个称为半开范围运算符 (..<) 的运算符。
for index in 0..<4 {
...
}
这将从 0 循环到 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()
Output:-
you've moved north
you've moved east
you've moved south
you've moved west
round the world
在 Swift 中快乐编码:-)
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")
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.