Swift 3:fatal error: Double value cannot be converted to Int because it is either infinite or NaN

前端 未结 2 1473
猫巷女王i
猫巷女王i 2021-01-17 16:54

When I call this method, an error received. How to handle NaN or infinite value during assign to hour, min or sec?

Here is my code:

private func se         


        
相关标签:
2条回答
  • 2021-01-17 17:27

    You should check if totalSeconds is a valid value, like:

    guard !(totalsSeconds.isNaN || totalSeconds.isInfinite) else {
        return "illegal value" // or do some error handling
    }
    

    And check this: Convert Float to Int in Swift

    0 讨论(0)
  • 2021-01-17 17:32

    Another option is to use a formatter for this, I just wanted to convert a Double to an Int to make it easier to display in my UI so a NumberFormatter was perfect, my Double was NaN so that's what the NumberFormatter provided me, rather than the fatalError that the Int 'cast' provided (why doesn't it return an optional like Int(String) does?)

    But in the context of this question a DateFormatter is a great solution, which would do the whole function's work for you (bear in mind that creating DateFormatters is a little costly so you wouldn't want to create one for every string formatting you do but keep it hanging out if it makes sense)

    0 讨论(0)
提交回复
热议问题