0

Today I switched to Swift 3 language. I am making an app that gives a countdown of days hours minutes and seconds until an event. The following code below displays the following in my app:

Optional(6) days Optional(59) minutes Optional(35) seconds.

My countdown in Swift 2 worked fine but once I converted it to Swift 3 the optional appeared in front of the numbers. Does anyone with experience in Swift 3 know a solution to this problem?

  @IBAction func NextWeeklyButtonPressed(_ sender: AnyObject) {
    let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTimeWeeks), userInfo: nil, repeats: true)
    timer.fire()        
   }

   func printTimeWeeks() {
    formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
    let startTime = Date()
    let endTime = formatter.date(from: WeeklyDate.text!+" 12:00:00 a")

    // WeeklyDate.text is a date in short style

    let timeDifference = (userCalendar as NSCalendar).components(requestedComponent, from: startTime, to: endTime!, options: [])

    WeeklyDateLabel.text = "\(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
Vojtech Ruzicka
  • 16,384
  • 15
  • 63
  • 66
ryanjigga
  • 3
  • 1
  • 2
    That means that `timeDifference.day` is an optional. Did you look up the DateComponents reference for Swift 3? – Martin R Oct 10 '16 at 06:03

2 Answers2

0

append ! to fields

WeeklyDateLabel.text = "\(timeDifference.day!) Days \(timeDifference.minute!) Minutes \(timeDifference.second!) Seconds"
Farhad Faramarzi
  • 425
  • 5
  • 15
0

You need to unwrap the optional Strings, e.g.

if let day = timeDifference.day, minute = timeDifference.minute, second = timeDifference.second {
  WeeklyDateLabel.text = "\(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
ff10
  • 3,046
  • 1
  • 32
  • 55