swift - 程序流程问题

标签 swift program-flow

我是 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/

相关文章:

ruby - 如何突破 Ruby 中的开始 block ?

php - 应该使用 `if ($a != NULL)` 还是 `if ($a !== NULL)` 来控制程序流?

Java 语言约定; setter/getter / setter/getter

swift - 如何在 Alamofire.request() 之外使用 JSON?

ios - 根据过滤器数组过滤 UICollectionView

swift - 按钮目标方法逻辑应该在 UIView 还是 UIViewController 中定义

ios - 如何在 AppDelegate 之外放置 FCM 的通知授权请求?

arrays - 检查多维数组中的值是否等于字符串 swift

c - 中断 C 中的程序流