gpt4 book ai didi

swift - var Double 类型 swift 崩溃

转载 作者:搜寻专家 更新时间:2023-11-01 05:37:07 25 4
gpt4 key购买 nike

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

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

关于swift - var Double 类型 swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35725748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com