user2662468 user2662468 -5 years ago 267
iOS Question

Unexpectedly found nil while unwrapping an optional value uitextfield

I know there are a lot of unexpected nil value questions here, but I've tried other approaches and they're not working for me. The function at the bottom is called from a button on another view controller. Basically the issue is that this code works as expected, the form element has the DatePicker as the input view, and it updates startDatePickerField.text when the value is changed, so I know that startDatePickerField.text is not empty, as it is displayed on the screen. However, when calling the testForValidity() function is called from another view controller containing the one we are working in, I get the "unexpectedly found nil while unwrapping option value error". All of the outlets are connected properly so I know it isn't that.

class popoverTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet var startDatePickerField: UITextField!

override func viewDidLoad() {
let startDatePicker:UIDatePicker = UIDatePicker()
startDatePicker.datePickerMode = UIDatePickerMode.dateAndTime
startDatePickerField.inputView = startDatePicker
startDatePicker.minuteInterval = 5
startDatePicker.addTarget(self, action: #selector(popoverTableViewController.startDatePickerValueChanged(_:)), for: UIControlEvents.valueChanged)

@IBAction func startDateDidBegin(_ sender: AnyObject) {

func startDatePickerValueChanged(_ sender: UIDatePicker) {

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.timeStyle = DateFormatter.Style.short
startDatePickerField.text = dateFormatter.string(from:
finishDateTime =


And the function that errors:

func testForValidity() {



Answer Source

At the top, add UITextFieldDelegate so it becomes:

class popoverTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { 

Then in viewDidLoad() add this line :

self.startDatePickerField.delegate = self
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download