2016-03-01 70 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() 
...