0

I am trying to add image with append in array of images, but XCode returns me an error "Generic parameter 'Element' could not be inferred"

DispatchQueue.main.async {
    self.picsArray.append(UIImage(data: try NSData(contentsOf: NSURL(string: "url") as! URL) as Data)!)
}
Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79
  • So break it into smaller pieces with temporary variables until you figure out which part is causing the problem. – Duncan C Dec 24 '16 at 21:11
  • XCode points an arrow under the function append – Bogdan Bogdanov Dec 24 '16 at 21:18
  • I broke it into let image = UIImage() and the dispatch puts this code: "as! @convention(block) () -> Void" after } – Bogdan Bogdanov Dec 24 '16 at 21:22
  • Note that this'll block the main thread while the image is being loaded from the URL, which generally isn't a good idea. Either move this to background thread (for example through using a global dispatch queue), or even better just use `URLSession` instead to load the data asynchronously (see [this Q&A](http://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift)). Also I would recommend using the `Data` and `URL` initialisers directly, rather than using the `NS` ones and casting. – Hamish Dec 24 '16 at 21:58

1 Answers1

0

The answer is in try. I executed it with ! and now it works :D

Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79
  • Well, it'll work until it fails to load data from the URL, at which point it'll explode. Handing the error with a do-catch block or a `try?` would be much more sensible. – Hamish Dec 24 '16 at 21:51