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.value == Int(self.value)
where self.value
is a double.
This checks if the rounded-down value of the double is the same as the double. Your variable could have an int or double value and Math. floor(variable) always has an int value, so if your variable is equal to Math. floor(variable) then it must have an int value.
main.swift var x = 25 if x is Int { print("The variable is an Int.") } else { print("The variable is not an Int.") }
Swift Character has a built-in property, isNumber , that can indicate whether the character represents a number or not. We use this property along with allSatisfy to check whether all the characters in a string are a number.
Try 'flooring' the double value then checking if it is unchanged:
let dbl = 2.0 let isInteger = floor(dbl) == dbl // true
Fails if it is not an integer
let dbl = 2.4 let isInteger = floor(dbl) == dbl // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With