Home > Software engineering >  Type of expression is ambiguous without more context - Swift
Type of expression is ambiguous without more context - Swift

Time:10-29

I'm getting this error here:

image.load(url: product?.productImage!)

The definition of the image:

@IBOutlet var image: CellImageView!

And here is my CellImageView class:

import UIKit

class CellImageView: UIImageView {
    var task: URLSessionDataTask!
    var imageCache = NSCache<AnyObject, AnyObject>()

    func load(url: String) {
        let real_url = url.replacingOccurrences(of: *image_path_here*, with: *image_path_here*)
        let imageUrl = URL(string: real_url)
        image = nil

        if let task = task {
            task.cancel()
        }

        if let imageFromCache = imageCache.object(forKey: imageUrl?.absoluteString as AnyObject) as? UIImage {
            image = imageFromCache
        }

        task = URLSession.shared.dataTask(with: imageUrl!, completionHandler: { data, _, error in
            guard let data = data, let newImage = UIImage(data: data) else {
                print(error)
                return
            }
            self.imageCache.setObject(newImage, forKey: imageUrl?.absoluteString as AnyObject)
            DispatchQueue.main.async {
                self.image = newImage
            }
        })
        task.resume()
    }
}

I don't know why this giving me an error. Can someone help me about this?

CodePudding user response:

This error (usually) occurs when the compiler can't infer and subsequently verify the types in the code. In this case you are calling

func load(url: String)

so the method is expexcting a String as a parameter. However you are calling it with a parameter of product?.productImage! which is an optional (the ! doesn't override the ? for the class, so it remains optional.

You need to handle the optional properly

if let product = product, productImage = product.productImage {
   image.load(url: productImage}
} 

You would probably be better rethinking your caching too. You are using a local parameter to hold the cache, so every time you create a new instance of the class you create a new empty cache. Also an imageView isn't the best place for a cache anyway; consider extracting all the networking and caching to a dedicated controller.

  • Related