Reputation: 9466
I have an input field that allows user to input numbers( the string is converted to a decimal), but there is an occasion where they could be a $ an no number, in that case I would like to use a guard and pop up an UIAlert letting the user know of the mistake. I read that there is a BOOL property of isNaN for Decimal in Swift 3, but I'm not entirely sure how to use it. This is what I'm trying
guard myDecimalNumber != isNaN else {
print("this is not a number show alert")
}
Upvotes: 2
Views: 231
Reputation: 539685
isNan
is a boolean property of Decimal
(and all floating point
types), so you can check it with
guard !myDecimalNumber.isNaN else {
// ... `myDecimalNumber` is NaN ...
}
But note that creating a Decimal
from a string returns an
optional which is nil
if the conversion fails, so what
you probably want is optional binding:
guard let myDecimalNumber = Decimal(string: textField.text) else {
// ... `textField.text` does not represent a number ...
}
(and the same approach works for other number types like
Double
, Int
, ...)
For proper handling of localized decimal separators, use a number formatter:
guard let myDecimalNumber = formatter.number(from: textField.text)?.decimalValue else {
// ... `textField.text` does not represent a number ...
}
Upvotes: 3