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.
Using @ColinE answer, I build an extension that handles when the Double cannot be converted to Int and another function that returns the Int:
extension Double {
func isInt() -> Bool {
guard Double(Int.min) <= self && self <= Double(Int.max) else {
return false
}
return floor(self) == self
}
func toInt() -> Int? {
guard Double(Int.min) <= self && self <= Double(Int.max) else {
return nil
}
return Int(self)
}
}
I hope this helps someone,
Xavi