2015-01-09 95 views
0

我试图创建一个应用程序,它将以格式HH:MM:SS显示时间。'字符串'不能转换为'Int'

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) 

在线 “让时间=(小时+山坳+分+山坳+秒)” 我不断收到错误“‘字符串’是无法转换为‘廉政’” 任何帮助将是很大的赞赏 谢谢, 尼克

+0

另外'components.hour'&CO的类型已经'Int' - 不需要使用'Int(components.hour)'。 – 2015-01-09 20:27:05

+0

而在'calendar.components(...)'中,您只需指定实际使用的组件(小时,分钟,秒)。 – 2015-01-09 20:44:09

回答

3

因为你想增加你得到的错误(又名,使用+StringInt实例在一起。

你也可以使用字符串插值:

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

或更好,但了解NSDateFormatter,它处理这更好:

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

let time = timeFormatter.stringFromDate(date)