Checking if a double value is an integer - Swift

后端 未结 12 1999
梦如初夏
梦如初夏 2020-12-14 14:18

I need to check if a double-defined variable is convertible to Int without losing its value. This doesn\'t work because they are of different types:

if self.         


        
12条回答
  •  时光说笑
    2020-12-14 14:41

    A small extension to check for this:

    extension FloatingPoint {
        var isInt: Bool {
            return floor(self) == self
        }
    }
    

    Then just do

    let anInt = 1.isInt
    let nonInt = 3.142.isInt
    

提交回复
热议问题