NSTimer:浮点值无法转换为UInt8,因为它大于UInt8.max

时间:2014-12-31 22:14:15

标签: xcode swift timer int nstimer

我的代码返回错误:致命错误:浮点值无法转换为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()
}

2 个答案:

答案 0 :(得分:3)

我会采用不同的方法,因为你需要多次表示NSTimeInterval,所以你应该考虑添加一个只读的计算属性作为项目的扩展,以返回它的字符串表示如下:

extension NSTimeInterval {
    var time:String {
        return String(format:"%d:%02d:%02d.%02d", Int(self/3600.0), Int((self/60.0) % 60), Int((self) % 60 ), Int(self*100 % 100 ))
    }
}

class ViewController: UIViewController {
    //declarations
    @IBOutlet weak var tappedLabel: UILabel!
    @IBOutlet weak var timerLabel: UILabel!

    var startTime = NSTimeInterval()
    var timer = NSTimer()

    //starts the timer
    func startTimer(sender: AnyObject) {
        if !timer.valid {
            timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: sender, selector: "updateTime", userInfo: nil, repeats:true)
            startTime = NSDate.timeIntervalSinceReferenceDate()
        }
    }
    // calculates the elapsed time in seconds (Double = NSTimeInterval).extension NStimeInterval
    func updateTime() {
        //find the difference between the current time and the start time and return a string out of it
                // updates the text field
        timerLabel.text = (NSDate.timeIntervalSinceReferenceDate() - startTime).time
    }

答案 1 :(得分:1)

UNint8只能存储高达64k(64 * 1024)的值。如果水桶已满,您就不能再填充它了。使用较大的存储桶Int将处理数以万计的数字。