var双重型swift崩溃

时间:2016-03-01 14:38:06

标签: swift double var

我正在制作一个计算器应用程序,当我达到一个很高的数字时它会崩溃。 这是代码。

var accumulator: Double = 0.0
 func updateDisplay() {
    // If the value is an integer, don't show a decimal point
     let iAcc = Int(accumulator)


    if accumulator - Double(iAcc) == 0 {
      numField.text = "\(iAcc)"

    } else {

        numField.text = "\(accumulator)"
    }
}

这是错误

fatal error: floating point value can not be converted to Int because it is greater than Int.max

如果有人能提供帮助那就太棒了!

1 个答案:

答案 0 :(得分:0)

您可以轻松使用此扩展程序来防止崩溃:

extension Double {
    // If you don't want your code crash on each overflow, use this function that operates on optionals
    // E.g.: Int(Double(Int.max) + 1) will crash:
    // fatal error: floating point value can not be converted to Int because it is greater than Int.max
    func toInt() -> Int? {
        if self > Double(Int.min) && self < Double(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}

所以,你的代码将是:

...
let iAcc = accumulator.toInt()
...