如何在函数全局中创建变量?

时间:2017-06-09 07:47:01

标签: ios swift swift3

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

当我尝试打印' runName'在DetailViewController中,runName的值为nil。我认为的问题是我无法在我添加的动作中设置全局变量,因为它在函数中。有没有其他方法可以获得这个变量的值并在函数之外使用它?

2 个答案:

答案 0 :(得分:1)

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
    )

  }

}

现在你可以在全班使用。

答案 1 :(得分:0)

由于@DSDharma指出即使' runName'被设置为全局变量,将其用作警报功能块内的全局变量,需要“自我”。关键字。

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

let runName = textField?.text

这需要改为:

self.runName = textField?.text