I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
Please check it on playground!
By the way in my Xcode
.toDouble() - doesn't exist
.doubleValue create value 0.0 from not numerical strings...
As already pointed out, the best way to achieve this is with direct casting:
Building from that, you can make a slick native Swift String extension:
This allows you to directly use:
Which will perform the casting for you. If Apple does add a
doubleValue
to the native String you just need to remove the extension and the rest of your code will automatically compile fine!Or you could do:
You can use StringEx. It extends
String
with string-to-number conversions includingtoDouble()
.It verifies the string and fails if it can't be converted to double.
Example: