简体   繁体   中英

Accessing a variable that is out of scope Swift

I know the is elementary stuff but I can't seem to get this. I have a function that takes the date pickers value, converts it to a string, assigns it to a variable, and them updates a labels text.

I want to be able to access that variable outside of the function so I can use it in prepareForSegue. So far I have tried making a global variable and updating it when the function is called but that didn't seem to work, and I have tried returning the value in the function but I must have done that wrong because it didn't work either.

The Function:

func datePickerChanged(datePicker:UIDatePicker) {
    var dateFormatter = NSDateFormatter()

    dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    var strDate = dateFormatter.stringFromDate(datePicker.date)
    dateTimeLabel.text = strDate
}

I want to get strDate out of the function. Any help is much appreciated!

You can do this in different ways.. You can use an inout parameter on a method to allow the method to update the parameter, like this:

var aString = ""

func doStuffWithA(inout theString: String) {

theString = "Groovy"
}

doStuffWithA(&aString) // changes aString to "Groovy"

Or you can declare the property outside of the method:

class SomeClass {
    var someString: String = ""

    func doStuff() {
        self.someString = "Groovy"
    }
 }

If you want this just for a segue, you can pass the object on performSegueWithIdentifier, like this:

func doStuff() {

    var aString = "Groovy"
    performSegueWithIdentifier("someSegue", sender: aString)

}

// Then here you can use it and assign it as a property on the next view controller

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "someSegue" {

         guard let aString = sender as? String else {

         return
         }

         let nextVC = segue.destinationViewController as! SomeVC
         nextVC.someProperty = aString
    }
}

If you want it to be accessible through out the class an out of function this is how you can do

class xyz {

   var startDate:String?

   func datePickerChanged(datePicker:UIDatePicker) {
      var dateFormatter = NSDateFormatter()
      dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
      dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

      self.startDate = dateFormatter.stringFromDate(datePicker.date)
      dateTimeLabel.text = self.startDate
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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