0

I've got one label startTime.text that displays a timestamp (hh:mm:ss), and I've got another label nextDose.text that I want to display the sum of startTime.text and the hours the user inputs into freq.text textfield. I've found that multiplying the number of hours by 3600 gives you the total amount of seconds to add to the timestamp to get the result I need, but I'm not getting the result I need. What am I doing wrong?

override func viewDidLoad() {
 super.viewDidLoad()
//the following code inputs the current time into the startTime label
 let dateFormatter = DateFormatter()

 dateFormatter.timeStyle = .medium

 let timeString = dateFormatter.string(from: Date() as Date)

 startTime.text = String(timeString)

 //the following code inputs the current time into the nextDose label

 let freqHour = Int(freq.text!)

 let hoursToSecs = Int(3600 * freqHour!)

 nextDose.text = String(hoursToSecs)
}

When I run the simulator, my tableview is the first thing I see, and when I click on the "+" symbol to add another item, the app crashes and I get this error: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) I haven't quite wrapped my head around Optionals, so I'm not sure how to proceed from here.

devil2pay
  • 3
  • 3
  • 1
    What is the point of using `Date() as Date` instead of simply `Date()` ? What is the point of `String(timeString)` instead of simply `timeString` ? – rmaddy Jun 24 '17 at 21:40
  • FYI - you have posted two completely separate an unrelated issues here. Please only post one issue per question. Keep this one focused on the date label. Post a second question on the crash but only have you spend some time searching on that error message. It has been covered many, many, many times before. – rmaddy Jun 24 '17 at 21:43
  • See https://stackoverflow.com/a/41232188/1226963 for how to add a given number of hours to a date. – rmaddy Jun 24 '17 at 21:48
  • @rmaddy To answer your first comment, to find the answer(s) to my problems, I've had to reutilize code from others' examples. Xcode never flagged the `Date() as Date` or `String(timeString)` so I assumed nothing was wrong. I've since deleted its so thank you. As for the `fatal error`, I did search for it before posting here, but could never nail down the correct answer until you posted the link. So again I thank you. I no longer have issues from this original post, but now different ones for yet another post. – devil2pay Jun 25 '17 at 23:47

0 Answers0