In Swift, how can one check if a string is a valid double value? I have been using the following extension from this question (but as a float) but if the value cannot be converted, it simply returns "0":
extension String {
var doubleValue:Double? {
return (self as NSString).doubleValue
}
}
Ideally, I would like it to return nil
so it can be caught in an if-let
, like so:
if let i = str.doubleValue {
object.price = i
} else {
// Tell user the value is invalid
}
Why not let it return
false
? Ortrue
of course.It is indeed more efficient not to create a number formatter every time we do a conversion:
Here is my function:
Just call it like this:
edit/update: Xcode 9 or later • Swift 4 or later
You can use Double initialiser StringProtocol to create an extension and use it to check if your string is a valid double as follow:
Testing