Im developing an image loading library in Swift 4 something like Kingfisher with some extensions to support loading images from URL into an UIImageView .
So then i can use this extension on a UICollection or UITableview cell with an UIImageView like this :
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: 
  "collectioncell", for: indexPath)
    if let normal = cell as? CollectionViewCell {
    normal.imagview.loadImage(fromURL:imageURLstrings[indexPath.row])
  }
Basically this is my extension Code , implementing the basic URLSession dataTask and Caching
public extension UIImageView {
public func loadImage(fromURL url: String) {
    guard let imageURL = URL(string: url) else {
        return
    }
    let cache =  URLCache.shared
    let request = URLRequest(url: imageURL)
    DispatchQueue.global(qos: .userInitiated).async {
        if let data = cache.cachedResponse(for: request)?.data, let 
           image = UIImage(data: data) {
             DispatchQueue.main.async {
                self.image = image
            }
        } else {
            URLSession.shared.dataTask(with: request, 
       completionHandler: { (data, response, error) in
            print(response.debugDescription)
                print(data?.base64EncodedData() as Any)
                print(error.debugDescription)
                if let data = data, let response = response, ((response as? HTTPURLResponse)?.statusCode ?? 500) < 300, let image = UIImage(data: data) {
                    let cachedData = CachedURLResponse(response: response, data: data)
                    cache.storeCachedResponse(cachedData, for: request)
                    DispatchQueue.main.async {
                       self.image = image
                    }
                }
            }).resume()
        }
    }
}
 }
Concluding i found out that sometimes if my URL is broken or i get 404 or even if i scroll the UICollectionView before all the images are completely downloaded, images are loaded into the wrong cell or i sometimes find duplicate images in collectionView but this does not happen if i use Kingfisher.
How do i prevent my extension from loading the wrong image into a cell or duplicating images?