Search code examples
swiftvariablesuidatepickerswift5

Extracting a variable from a function in Swift


Im sure there is a simple answer to this but Im a newbie and I cannot figure out how to capture a simple string to a variable to use it everywhere in code. Im just trying to get the date from UIDatePicker and not just use it in a label.

    @IBAction func datePicker(_ sender: UIDatePicker)   {

        let dateFormater: DateFormatter = DateFormatter()
        dateFormater.dateFormat = "yyyy-MM-dd"
        let stringFromDate: String = dateFormater.string(from: self.datePicker.date) as String

              print(stringFromDate)
        // dateDisplay.text = stringFromDate
        return
   }

Any direction would be appreciated.


Solution

  • If you have a var in the same UIViewController as the datePicker, that var will get filled with the date string when datePicker is called. You can pass that value when segueing in or out of this or other UIViewControllers

    var selectedDate: String?
    
    @IBAction func datePicker(_ sender: UIDatePicker) {
        selectedDate = self.datePicker.date
    }
    

    If, in another file, you create a static function as part of another class, you can store the date string there. This isn't really great coding practice, unless you are putting all your logic into a coordinator, or similar type coding.

    class BigMessyDataHolder {
        static var selectedDate: Date?
    }
    

    and then in your code, call it like this:

       @IBAction func datePicker(_ sender: UIDatePicker) {
            BigMessyDataHolder.selectedDate = self.datePicker.date
       }
    

    And then access the dateFormatter from wherever