1

我在 Swift 上有点像新手,很难理解处理事物的逻辑流程。我的程序中有几件事似乎以我不期望的顺序运行,在下面的代码中,我需要执行函数“getValues”(当用户从​​我的摘要中选择了一行时桌子)

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
    } else {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: true)
    gameNo = indexPath.row

    getValues()

    vRatings.append(defRat[0])
    hRatings.append(defRat[1])
    self.performSegue(withIdentifier: "gameSelected", sender: self)
}

func getValues() { // (it is here where the array "defRat" gets populated 

但是,当我在调试模式下浏览代码时,会跳过对 getValues 的调用。来自传统编码(COBOL、FORTRAN 等)的背景,这对我来说毫无意义。该程序因非法索引而崩溃,因为从未填充过“defRat”数组。

希望有一个简单的答案......提前非常感谢。

4

1 回答 1

0

而不是func getValues() {,做func getValues() -> [String] {。(将 String 替换为数组中的任何数组。)然后,您可以返回一个 String 数组(或任何类型的 defRat),而不是更新 defRat。在tableView函数中,替换getValues()为,追加时var exampleVar = getValues()可以替换为。总之,它应该是这样的:defRatexampleVar

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
    } else {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: true)
    gameNo = indexPath.row

   var exampleVar =  getValues()

    vRatings.append(exampleVar[0])
    hRatings.append(exampleVar[1])
    self.performSegue(withIdentifier: "gameSelected", sender: self)
}

func getValues() -> [String] {
    //Whatever code is being executed here

    var foo:[String]  = []
    //More stuff happens that changes foo
    return foo
}
于 2018-03-21T01:15:27.920 回答