Issue #63

Codable in Swift 4 changes the game. It deprecates lots of existing JSON libraries.

Generic model

API responses is usually in form of an object container with a key. Then it will be either nested array or object. We can deal with it by introducing a data holder. Take a look DataHolder

{
  "data": [
    {
      "comment_id": 1
    },
    {
      "comment_id": 2
    }
  ]
}
struct ListHolder<T: Codable>: Codable {
  enum CodingKeys: String, CodingKey {
    case list = "data"
  }

  let list: [T]
}

struct OneHolder<T: Codable>: Codable {
  enum CodingKeys: String, CodingKey {
    case one = "data"
  }

  let one: T
}

then with Alamofire, we can just parse to data holder

func loadComments(mediaId: String, completion: @escaping ([Comment]) -> Void) {
  request("https://api.instagram.com/v1/media/\(mediaId)/comments",
    parameters: parameters)
  .responseData(completionHandler: { (response) in
    if let data = response.result.value {
      do {
        let holder = try JSONDecoder().decode(ListHolder<Comment>.self, from: data)
        DispatchQueue.main.async {
          completion(holder.list)
        }
      } catch {
        print(error)
      }
    }
  })
}

Read more