iosswiftuikituiimage

Convert UIImage.size to String


if(image != nil){
    mediaSize = String(image!.size.width) + "|" + String(image!.size.height)
}

The result should be like "400|300"

I get the error: No exact matches in call to initializer

image is UIImage and I'm uploading it to the server before I try to convert the size to string and it's valid

Other questions about this aren't helping


Solution

  • The problem is that both height and width are CGFloat, which cannot be directly converted to a String using String.init.

    You can either convert them to Double and then initialise a String from the Double

    guard let image else { return }
    let width = Double(image.size.width)
    let height = Double(image.size.height)
    mediaSize = String(width) + "|" + String(height)
    

    Or simply use String interpolation, which does support CGFloat.

    mediaSize = "\(image.size.width) | \(image.size.height)"
    

    However, be aware that you're converting floating point numbers to a String, so you might end up with a non user friendly value with tons of decimal places. If you know that your values are integers, convert them to integers using Int(image.size.width) or format them to a fixed number of decimal places using either String(format:_:) or a NumberFormatter.