繁体   English   中英

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

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

我目前有以下名为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)

}

我的问题是,当用户单击警报控制器上的“确定”并在以下函数中使用它时,我试图从添加的操作中提取“ runName”:

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

当我尝试在DetailViewController中打印'runName'时,runName的值为nil。 我认为的问题是,无法像在函数中那样在添加的操作中设置全局变量。 我还有其他方法可以获取此变量的值并在函数外部使用它吗?

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
    )

  }

}

现在,您可以在全班使用。

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

例如,在警报功能块中包含以下内容之前:

let runName = textField?.text

这需要更改为:

self.runName = textField?.text

暂无
暂无

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

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