Trouble with program flow

32 views Asked by At

I am somewhat of a novice at Swift, and am having a difficult time understanding the logical flow in which things are being processed. There are a couple of things in my program that seem to be running in a sequence that I'm not expecting, in In the following code, I need to perform the function "getValues" (when the user has selected a row from my summary table)

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 

However, when I walk through the code in debug mode, the call to getValues just gets skipped over. Coming from a background of traditional coding (COBOL, FORTRAN, etc), this makes no sense to me. The program is blowing up on illegal indexing, because the 'defRat' array was never populated.

Hopefully, there is a simple answer...many thanks in advance.

1

There are 1 answers

0
Ben A. On

Instead of func getValues() {, do func getValues() -> [String] {. (Replace String with whatever the array is in the array.) Then, instead of updating defRat, you can return an array of String (or whatever type defRat is). In the tableView function, replace getValues() with var exampleVar = getValues(), and you can replace defRat when you append with exampleVar. All together, it should look like this:

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
}