【发布时间】:2014-12-31 22:14:14
【问题描述】:
我的代码返回错误:致命错误:浮点值无法转换为 UInt8,因为它大于 UInt8.max。按下按钮时会调用代码(在不同的 swift 文件中),但我知道问题不在于调用函数,所以我没有包含它。
代码:
//starts the timer
func startTimer(sender: AnyObject)
{
if !timer.valid
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: sender, selector: Selector(updateTime()), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
//disp = timerDisplay
}
}
//function that configures the timer
func updateTime()
{
var currentTime = NSDate.timeIntervalSinceReferenceDate()
//find the difference between the current time and the start time
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the seconds in elapsed time
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
///find out the fraction of milliseconds to be displayed
let fraction = UInt8(elapsedTime * 10)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
//let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)
//display the time left to a string
timerDisplay = "\(strSeconds):\(strFraction)"
}
func stopTimer()
{
timer.invalidate()
}
【问题讨论】:
-
有什么问题?
-
@recursive 我想知道如何解决错误并让代码正常工作。
-
我明白了。这个问题基本上在帖子标题中解释了。请问您为什么使用
UInt8?它最多只能存储 255 个值,因此会受到限制。 -
这就是教程所说的。我尝试了 UInt16,并得到了同样的错误。尝试 Uint32 或 Uint64 时,应用程序崩溃并且没有错误
-
错误信息专门针对
UInt8,所以如果您尝试UInt16并得到同样的错误,您可能没有执行您认为的代码。
标签: xcode swift timer int nstimer