2016-03-01 72 views
2

我正在制作一个计算器应用程序,当它达到高数量时它崩溃。 这是代码。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 

如果任何人能帮助这将是伟大的!

+0

什么是'accumulator',你可以在运行时打印'accumulator'? – Breek

回答

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