致命错误:索引超出范围(数组)

时间:2016-12-20 20:48:28

标签: arrays swift swift3 fatal-error

我对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])

屏幕:

Screen

1 个答案:

答案 0 :(得分:0)

错误在于:

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