var Double 类型 swift 崩溃
var Double type swift crashing
我正在制作一个计算器应用程序,当我得到一个很大的数字时它崩溃了。
这是代码。
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
如果有人能提供帮助那就太好了!
您可以轻松使用此扩展来防止崩溃:
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()
...
我正在制作一个计算器应用程序,当我得到一个很大的数字时它崩溃了。 这是代码。
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
如果有人能提供帮助那就太好了!
您可以轻松使用此扩展来防止崩溃:
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()
...