title: How to put image to NSCache in Swift?
body: <p>I make some code using swift 4 to load image from URL, but every time I add images to server, it took a lot of time to load it in colection view or table view. I want to try store it in NScache but i dont understand to do it. can anyone help me, I'm new in swift :(</p>
  <pre><code>@objc func loadPosts() {
      
      let url = URL(string: &quot;http://someURL/Url.php&quot;)!
  
      var request = URLRequest(url: url)
      request.httpMethod = &quot;POST&quot;
      
      let body = &quot;phomepost=\(homepost)&quot;
      
      request.httpBody = body.data(using: String.Encoding.utf8)
      
      URLSession.shared.dataTask(with: request) { data, response, error in
          DispatchQueue.main.async(execute:  {
              if error == nil {
                  do{
                      let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                      
                      self.comments.removeAll(keepingCapacity: false)
                      self.images.removeAll(keepingCapacity: false)
                      self.collectionView?.reloadData()
                      
                      guard let parseJSON = json else {
                          print(&quot;Error While Parsing&quot;)
                          return
                      }
                      
                      guard let posts = parseJSON[&quot;posts&quot;] as? [AnyObject] else {
                          print(&quot;Error while parseJSONing&quot;)
                          
                          return
                      }
                      self.comments = posts.reversed()
                      
                      for i in 0 ..&lt; self.comments.count {
                          let path = self.comments[i][&quot;path&quot;] as? String
                          
                          if !path!.isEmpty {
                              let url = NSURL(string: path!)!
                              let imageData = try? Data(contentsOf: url as URL)
                              let image = UIImage(data: imageData! as Data)!
                              self.images.append(image)
                      
                          } else {
                              let image = UIImage()
                              self.images.append(image)
                          }
                      }
                      self.collectionView?.reloadData()
                      //print(posts.count)
                  } catch {
                      print(error)
                  }
              }else{
                  print(error)
              }
          })
      }.resume()
  }
  </code></pre>