Mr10k
Mr10k

Reputation: 157

How can I make a variable inside a function global?

I currently have the following function called saveRun()

func saveRun() {

    let startLoc = locations[0]
    let endLoc = locations[locations.count - 1]
    let startLat = startLoc.coordinate.latitude
    let startLong =  startLoc.coordinate.longitude
    let endLat = endLoc.coordinate.latitude
    let endLong = endLoc.coordinate.longitude

    //1. Create the alert controller
    let alert = UIAlertController(title: "Save the Run", message: "Choose a name: ", preferredStyle: .alert)

    //2. Add the text field
    alert.addTextField { (textField) in
        textField.text = ""
    }

    // 3. Grab the value from the text field, and print it when the user clicks OK
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0] // Force unwrapping because we know it exists.

        // Create name for run
        let runName = textField?.text
        let run = self.databaseRef.child(runName!)
        let user = FIRAuth.auth()?.currentUser?.uid

        // Enter run info into db
        run.child("startLat").setValue(startLat)
        run.child("startLong").setValue(startLong)
        run.child("endLat").setValue(endLat)
        run.child("endLong").setValue(endLong)
        run.child("distance").setValue(self.distance)
        run.child("time").setValue(self.seconds)
        run.child("user").setValue(user)

        // Enter locations into db

        var i = 0
        for location in self.locations {

            run.child("locations").child("\(i)").child("lat").setValue(location.coordinate.latitude)
            run.child("locations").child("\(i)").child("long").setValue(location.coordinate.longitude)
            i = i + 1

        self.performSegue(withIdentifier: DetailSegueName, sender: nil)


        }



    }))

    // 4. Present the alert
    self.present(alert, animated: true, completion: nil)

}

My problem is that I am trying to extract 'runName' from the action that I am adding when the user clicks 'Ok' on the alert controller and using it in the following function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let detailViewController = segue.destination as? DetailViewController {
        detailViewController.runName = self.runName
    }
}

When I try to print 'runName' in DetailViewController, the value of runName is nil. The issue I think is that I cannot set a global variable inside the action I have added as it is in a function. Is there any other way I can obtain this variable's value and use it outside of the function?

Upvotes: 0

Views: 1061

Answers (2)

Dharma
Dharma

Reputation: 3013

Class YourClassName:UIViewController {

  var  runName:String = "" // This will be global for your class 

  //Remove local decalration of runName variable
  func saveRun() { // your function


    alert.addAction(

      //.....
      self.runName = textfield?.text
    )

  }

}

Now you can use in whole class.

Upvotes: 1

Mr10k
Mr10k

Reputation: 157

I solved this thanks to @DSDharma pointing out that even if 'runName' was set as a global variable, using it as a global variable inside of an alert function block required the 'self' keyword.

For example, before I had the following inside of the alert function block:

let runName = textField?.text

This needed to be changed to:

self.runName = textField?.text

Upvotes: 0

Related Questions