Swift中意外的除法结果

时间:2014-10-28 23:30:48

标签: swift division

我正在尝试在Swift中创建一个节拍器应用程序,并且我有一些尴尬的结果。这是代码:

 @IBAction func playStop(sender: AnyObject) {
    if !timer.valid{
        println(Double(60/tempo))
        timer = NSTimer(timeInterval: NSTimeInterval(Double(60/(tempo))), target: self, selector: "update", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
    }
    else{
        timer.invalidate()
    }
}
func control(_control: NSControl,
    textShouldEndEditing fieldEditor: NSText) -> Bool
{
    if (tempoLabel.integerValue <= 0)
    {
        return false
    }
    tempo = tempoLabel.integerValue
    timer.invalidate()
    println(tempo)
    playStop(self)
    return true

}

用户将速度设置为带有数字格式化程序的NSTextfield,默认情况下设置为60。当更改文本字段的值时,控制台显式写入tempo变量的正确值,并且仅当速度设置为60时程序才能正常工作。当值不是60时,每次都得到Double(60/tempo)等于0的结果,update函数被调用,好像处于无限循环中一样。使用Double(60/tempo)Float(60/tempo)60/tempo不会改变任何内容。我不明白为什么会得到这样的结果,或者我怎么解决它。

1 个答案:

答案 0 :(得分:1)

将分子或分母转换为加倍。

执行60.0 / tempo或60 / Double(速度)