Nick Greenway
Nick Greenway

Reputation: 31

'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

Upvotes: 1

Views: 442

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

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)

Upvotes: 3

Related Questions