【问题标题】:var Double type swift crashingvar Double 类型 swift 崩溃
【发布时间】:2016-06-14 00:55:23
【问题描述】:

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

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

如果有人能帮忙那就太好了!

【问题讨论】:

  • 什么是accumulator,你能在运行时打印accumulator吗?

标签: swift double var


【解决方案1】:

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

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()
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2014-12-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多