I am using a date picker and want to assign the value from it to an object property. But for some reason this does not happen and the object property contains nil.
I put code next to it where a date value is assigned to a simple property. It works.
Please tell me what's the matter here? How do I store a date into a property of an object?
import UIKit
struct NewDate {
var date: Date?
}
class MyViewController: UIViewController {
var newDate: NewDate?
@IBOutlet weak var pickerOutlet: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
let date = pickerOutlet.date
print(date) // Prints: 2021-09-03 03:56:17 +0000
newDate?.date = pickerOutlet.date
print(newDate?.date) // Prints: nil
}
}
You have to create it first:
newDate = NewDate()
here:
override func viewDidLoad() {
super.viewDidLoad()
let date = pickerOutlet.date
print(date) // Prints: 2021-09-03 03:56:17 +0000
newDate = NewDate() // <<-- Add this
newDate?.date = pickerOutlet.date
print(newDate?.date) // Prints: nil
}