你好,我正在努力学习敏捷。我对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
发布于 2020-05-28 04:04:16
在试图访问第四个索引的代码中,由于您使用了.循环控制语法。第四个索引没有排列。
以下是有关快速循环的一些详细信息。
for index in 0...4 {
 ...
}上面的片段说,从0开始迭代范围,包括从0到4的4。
如果不希望包含4,则使用这个称为半开范围运算符(..<)。
for index in 0..<4 {
 ...
}这将从0循环到3,并停止执行。
发布于 2020-05-28 03:57:46
在loop...but中,有更有效的方法来更好地理解您实现了什么.
我已经更新了您的code...it将正常运行。
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 worldSwift中的愉快编码:-)
发布于 2020-05-28 04:00:40
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")
                        }
        }
    }
}https://stackoverflow.com/questions/62056744
复制相似问题