我是 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
但是,当我在 Debug模式下浏览代码时,对 getValues 的调用被跳过了。来自传统编码(COBOL、FORTRAN 等)的背景,这对我来说毫无意义。该程序因非法索引而崩溃,因为从未填充“defRat”数组。
希望有一个简单的答案...提前致谢。
最佳答案
代替 func getValues() {
,执行 func getValues() -> [String] {
。 (将 String 替换为数组中的任何数组。)然后,您可以返回一个 String 数组(或 defRat 的任何类型),而不是更新 defRat。在tableView
函数中,将getValues()
替换为var exampleVar = getValues()
,即可替换defRat
当您追加 exampleVar
时。总之,它应该是这样的:
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
}
关于swift - 程序流程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393137/