Swift 2 Update
There are new failable initializers that allow you to do this in more idiomatic and safe way (as many answers have noted, NSString's double value is not very safe because it returns 0 for non number values. This means that the doubleValue
of "foo"
and "0"
are the same.)
let myDouble = Double(myString)
This returns an optional, so in cases like passing in "foo"
where doubleValue
would have returned 0, the failable intializer will return nil
. You can use a guard
, if-let
, or map
to handle the Optional<Double>
Original Post:
You don't need to use the NSString constructor like the accepted answer proposes. You can simply bridge it like this:
(swiftString as NSString).doubleValue
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…