Search code examples
swiftintnsdatenscalendar

'String' is not convertible to 'Int'


I'm trying to create an app that will display the time in format HH:MM:SS.

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute |                       
.CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay | .CalendarUnitSecond,
fromDate:      date)
let hour = Int(components.hour)
let minutes = Int(components.minute)
let second = Int(components.second)
let col = ":"
let time = (hour+col+minutes+col+second)

On line "let time = (hour+col+minutes+col+second)" I keep getting the error "'String' is not convertible to 'Int'" Any help would be greatly appreciated Thanks, Nick


Solution

  • You're getting that error because you're trying to add (aka, use +) String and Int instances together.

    You could instead use string interpolation:

    let time = "\(hour):\(minutes):\(second)"
    

    or better yet, learn about NSDateFormatter, which handles this much better:

    let timeFormatter = NSDateFormatter()
    timeFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("HH:mm:ss", options: 0, locale: NSLocale.currentLocale())
    
    let time = timeFormatter.stringFromDate(date)