skip to Main Content
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

2

Answers


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

    Login or Signup to reply.
  2. You can also use String(format:...):

    var mediaSize: String = ""
    let image = UIImage(named: "myImage")
    if let image {
        mediaSize = String(format: "%0.0f|%0.0f", image.size.width, image.size.height)
        print(mediaSize)
    }
    

    The %0.0f means convert float to string, with NO decimals.

    So your result would be "400|300"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search