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
As of Swift 2.0, the Double
type has a failable initializer that accepts a String
. So the safest way to go from String
to CGFloat
is:
let string = "1.23456"
var cgFloat: CGFloat?
if let doubleValue = Double(string) {
cgFloat = CGFloat(doubleValue)
}
// cgFloat will be nil if string cannot be converted
If you have to do this often, you can add an extension method to String
:
extension String {
func CGFloatValue() -> CGFloat? {
guard let doubleValue = Double(self) else {
return nil
}
return CGFloat(doubleValue)
}
}
Note that you should return a CGFloat?
since the operation can fail.