0

Building the ToDo app. The app crashes when the new todo task is created.

The breakpoint stops the code and returns:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

 @IBAction func doneButton(_ sender: UIButton) {
    guard let title = textView.text, !title.isEmpty else {
        return
    }

    let todo = Todo(context: managedContext)
    todo.title = title
    todo.priority = Int16(segmentedControl.selectedSegmentIndex)
    todo.date = Date()

    do {
        try managedContext.save()
        dismiss(animated: true)
        textView.resignFirstResponder()

    } catch {
        print("Error saving todo: \(error)")

    }

}
@IBAction func cancelButton(_ sender: UIButton) {
    dismiss(animated: true)
    textView.resignFirstResponder() 
}

Any ideas what could have caused the app crash? Thanks

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
evgen
  • 23
  • 6
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Prashant Tukadiya Apr 12 '18 at 06:29
  • How do you declare `textView`? And the `segmentedControl`? If those are IBOutlets, make sure they're hooked up properly in the storyboard. – LinusGeffarth Apr 12 '18 at 06:29
  • @LinusGeffarth IBOutlet weak var textView: UITextView! – evgen Apr 12 '18 at 06:29
  • This is common error found for beginners .Search it in google you find Thousands of answer – Prashant Tukadiya Apr 12 '18 at 06:30
  • Are they connected with the storyboard properly? – LinusGeffarth Apr 12 '18 at 06:30
  • @LinusGeffarth yeah. Connected properly IBOutlet weak var textView: UITextView! IBOutlet weak var segmentedControl: UISegmentedControlSegment! – evgen Apr 12 '18 at 06:35

1 Answers1

1

UISegmentedControlSegment is the public enum and UISegmentedControl is the UIControl As per your comment, it seems that you have mistaken UISegmentedControl for UISegmentedControlSegment, so connect UISegmentedControl like below:

@IBOutlet weak var segmentedControl: UISegmentedControl!
Mansi
  • 628
  • 1
  • 8
  • 18