简体   繁体   English

如何在函数内部创建变量?

[英]How can I make a variable inside a function global?

I currently have the following function called saveRun() 我目前有以下名为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: 我的问题是,当用户单击警报控制器上的“确定”并在以下函数中使用它时,我试图从添加的操作中提取“ runName”:

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. 当我尝试在DetailViewController中打印'runName'时,runName的值为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? 我还有其他方法可以获取此变量的值并在函数外部使用它吗?

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. 现在,您可以在全班使用。

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. 我感谢@DSDharma解决了这一问题,他指出,即使将'runName'设置为全局变量,将其用作警报功能块内部的全局变量也需要'self'关键字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM