0

I'm trying to create an application that notifies you every hour based on the start time you insert into a text field. I have an if statement that checks if the value of the text field is nil, and puts in some default notification times if the text field is nil. However, I'm getting the error "Unexpectedly found nil while unwrapping an Optional value". I'm not sure why this is happening. I'm a beginner, in Xcode, and in coding in general, so I apologize if this is question has an obvious solution.

Heres the code:

Note: the titles of the text fields are HourOneHourlyUN and MinuteOneHourlyUN

      if HourOneHourlyUN == nil || MinuteOneHourlyUN == nil {

            dateComponents1.hour = 9
            dateComponents1.minute = 00

            dateComponents2.hour = 10
            dateComponents2.minute = 00

            dateComponents3.hour = 11
            dateComponents3.minute = 00

            dateComponents4.hour = 12
            dateComponents4.minute = 00

            dateComponents5.hour = 13
            dateComponents5.minute = 00

            dateComponents6.hour = 14
            dateComponents6.minute = 00

        } else {
           dateComponents1.hour = Int(HourOneHourlyUN.text!)
           dateComponents1.minute = Int(MinuteOneHourlyUN.text!)

           dateComponents2.hour = Int(HourOneHourlyUN.text!)! + 1
           dateComponents2.minute = Int(MinuteOneHourlyUN.text!)

           dateComponents3.hour = Int(HourOneHourlyUN.text!)! + 2
           dateComponents3.minute = Int(MinuteOneHourlyUN.text!)

           dateComponents4.hour = Int(HourOneHourlyUN.text!)! + 3
           dateComponents4.minute = Int(MinuteOneHourlyUN.text!)

           dateComponents5.hour = Int(HourOneHourlyUN.text!)! + 4
           dateComponents5.minute = Int(MinuteOneHourlyUN.text!)

           dateComponents6.hour = Int(HourOneHourlyUN.text!)! + 5
           dateComponents6.minute = Int(MinuteOneHourlyUN.text!)
        }

Thank you in advance!

drew.ss
  • 3
  • 3
  • 5
    You are not checking if the text is nil, but if the TextField is nil – Sajjon May 06 '20 at 19:29
  • 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) – TylerP May 06 '20 at 19:43

1 Answers1

0

You are checking if the textfield is null, instead to check if the text contained inside the textfield is null. You have to correct the first if as below

if HourOneHourlyUN.text == nil || MinuteOneHourlyUN.text == nil {
     // Code
}
Andrea
  • 249
  • 1
  • 5