【问题标题】:'String' is not convertible to 'Int''String' 不能转换为 'Int'
【发布时间】:2015-01-09 20:15:45
【问题描述】:

我正在尝试创建一个以 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)

在线 “让时间=(小时+列+分钟+列+秒)” 我不断收到错误“'String' 不能转换为 'Int'” 任何帮助将不胜感激 谢谢, 尼克

【问题讨论】:

  • 另外,components.hour &co 已经属于 Int 类型 - 无需使用 Int(components.hour)
  • 而在calendar.components(...) 中您只需要指定实际使用的组件(小时、分钟、秒)。

标签: swift int nsdate nscalendar


【解决方案1】:

您收到该错误是因为您尝试同时添加(也就是使用 +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)

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 2014-10-16
    • 2018-02-28
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多