Converting CGFloat to String in Swift

iamktothed picture iamktothed · Aug 6, 2014 · Viewed 30.3k times · Source

This is my current way of converting a CGFloat to String in Swift:

let x:Float = Float(CGFloat)
let y:Int = Int(x)
let z:String = String(y)

Is there a more efficient way of doing this?

Answer

drewag picture drewag · Aug 6, 2014

You can use string interpolation:

let x: CGFloat = 0.1
let string = "\(x)" // "0.1"

Or technically, you can use the printable nature of CGFloat directly:

let string = x.description

The description property comes from it implementing the Printable protocol which is what makes string interpolation possible.