【问题标题】:Fatal error: Index out of range (Arrays)致命错误:索引超出范围(数组)
【发布时间】:2017-05-06 04:22:08
【问题描述】:

我对 Swift 和编程很陌生,所以我不知道问题出在哪里。试图在现有主题中找到答案 - 找不到。提前致谢。

func smartAssigning(names: [String], statuses: [Bool], projects: [Int], tasks: [Int]) -> String {
    //beginig
    var collect: [Int] = [], nameLast = 0
    var candidateNumber: [Int] = []
    for x in 0...statuses.count {

        //Defines who is working
        if statuses[x] == false {
            collect.append(x)
        } else {}
    }

    // Checks for min tasks assigned among those not on vacation
    let rt: Int = tasks.min()!
    let rp: Int = projects.min()!
    for i in collect {
        if tasks[i] == rt {
            candidateNumber.append(i)
        } else {}
    }
    // if there is only 1 with min tasks - returns his number in array
    if candidateNumber.count == 1 {
        nameLast = candidateNumber[0]
    } else {
        // checks for min projects
        for e in candidateNumber {
            if projects[e] == rp {
                nameLast = e
            }
        }
    }
    return names[nameLast]
}
smartAssigning(names: ["sd", "dfsd","dfsdf"], statuses: [true, false, false], projects: [2, 1, 1], tasks: [3, 2, 1])

屏幕:

【问题讨论】:

  • 第一个错误在for x in 0...statuses.count– 您是否尝试调试问题?单步执行函数会很快发现问题。
  • 名称、状态、项目和任务数组中的元素是否都绑定在一起?例如。名字与第一个状态、第一个项目和第一个任务相关联?
  • 是的,他们是。但是我发现了我的问题。感谢您和 Martin R. Damn。太简单。为什么 XCODE 不将其识别为错误?
  • @JackMov 因为这是运行时错误。

标签: arrays swift swift3 fatal-error


【解决方案1】:

错误在这里:

for x in 0...statuses.count { // Error is here

    //Defines who is working
    if statuses[x] == false {
        collect.append(x)
    } else {}
}

如果statuses.countn,那么最大索引是n-1。应该是0..<statuses.count。您应该避免手动创建这样的范围,因为它可能会导致这种错字。最好只做for x in status.indices

顺便说一句,如果else 不做任何事情,则不需要它。

另外,不要与 false (== false) 进行比较,只需否定 Bool

for x in statuses.indices { // Error is here
    //Defines who is working
    if !statuses[x] {
        collect.append(x)
    }
}

整个代码可以使用单个filter(_:) 表达式编写:

// TODO: Give me a new meaningful name!
let collect = statues.enumerated() // Get index, status pairs
                     .filter{ index, status in !status } // filter all false statuses
                     .map{ index, status in index } // Take just the indices

【讨论】:

  • 谢谢。发现第一个错误?看起来它在 XCODE 中工作,但不想在 CODECHALLENGE 窗口中工作。说:file.swift on line 15:24: error: value of type '[Int]' has no member 'min' if tasks[i] == tasks.min() { ^~~~~ ~~~跨度>
  • 我不知道你在说什么。 o.0'
  • IDK,打开一个新问题。好像应该没问题
  • 我找到了原因。他们使用 Swift 2,它需要 array.minElement() 而不是 array.min()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多