Swift 3:致命错误:无法将双精度值转换为Int,因为它是无穷大或NaN

Swift 3:致命错误:无法将双精度值转换为Int,因为它是无穷大或NaN,swift,Swift,调用此方法时,收到一个错误。如何在分配给小时、分钟或秒期间处理NaN或无限值 这是我的密码: private func secondsToFormattedString(totalSeconds: Float64) -> String{ let hours:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 86400) / 3600) let minutes:Int = Int(totalSeconds.trun

调用此方法时,收到一个错误。如何在分配给小时、分钟或秒期间处理NaN或无限值

这是我的密码:

private func secondsToFormattedString(totalSeconds: Float64) -> String{
    let hours:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 86400) / 3600)

    let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
    let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60))

    if hours > 0 {
        return String(format: "%i:%02i:%02i", hours, minutes, seconds)
    } else {
        return String(format: "%02i:%02i", minutes, seconds)
    }
}

您应该检查
totalSeconds
是否为有效值,如:

guard !(totalsSeconds.isNaN || totalSeconds.isInfinite) else {
    return "illegal value" // or do some error handling
}
并检查以下内容:

另一个选择是使用格式化程序,我只是想将Double转换为Int,以便更容易在我的UI中显示,因此
NumberFormatter
是完美的,我的Double是NaN,所以这是
NumberFormatter
提供给我的,而不是Int“cast”提供的
fatalError
(为什么不像Int(String)那样返回可选值?)


但是在这个问题的上下文中,
DateFormatter
是一个很好的解决方案,它可以为您完成整个函数的工作(请记住,创建
DateFormatter
s的成本有点高,所以您不希望为您所做的每种字符串格式都创建一个,但如果有意义,请将其挂起)

考虑使用
TimeInterval
datecomponents格式
当问题发生时,如何调用函数以及totalSeconds的值是多少?–一个独立的、可复制的测试用例会很有帮助。nan或无穷大都不是有限的,所以你可以说
guard totalSeconds.isFinite,否则{…}
@Hamish你完全正确。我只是想指出不同的API,因为最初的问题明确提到了NaN和Infinity。