stringswiftcgfloat

Converting CGFloat to String in Swift


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?


Solution

  • 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.