I\'m new to Swift, how can I convert a String to CGFloat?
I tried:
var fl: CGFloat = str as CGFloat
var fl: CGFloat = (CGFloat)str
var fl: CGFloat = CGFl
If you want a safe way to do this, here is a possibility:
let str = "32.4"
if let n = NSNumberFormatter().numberFromString(str) {
let f = CGFloat(n)
}
If you change str
to "bob", it won't get converted to a float, while most of the other answers will get turned into 0.0.
For Swift 3.0, I'd do something like this:
let str = "32.4"
guard let n = NSNumberFormatter().number(from: str) else { return }
// Use `n` here
In Swift 4, NSNumberFormatter
has been renamed to NumberFormatter
:
let str = "32.4"
guard let n = NumberFormatter().number(from: str) else { return }