Skip to content

Instantly share code, notes, and snippets.

@marinbenc
Last active January 24, 2017 09:59
Show Gist options
  • Select an option

  • Save marinbenc/36be816f7b100a8fa7ccc15d329f4db0 to your computer and use it in GitHub Desktop.

Select an option

Save marinbenc/36be816f7b100a8fa7ccc15d329f4db0 to your computer and use it in GitHub Desktop.
Make a Swift Array conform to Decodable (for JSON parsing)
typealias JSON = Any
public protocol Decodable {
init?(_ json: JSON)
}
extension Array: Decodable {
public init?(_ json: JSON) {
guard let jsonArray = json as? [JSON] else {
return nil
}
if let decodableType = Element.self as? Decodable.Type {
self.init()
let elements = jsonArray.flatMap { json in
return decodableType.init(json) as? Element
}
self.append(contentsOf: elements)
} else {
return nil
}
}
}
//Usage:
struct User: Decodable {
let name: String
init?(_ json: JSON) {
guard let jsonDict = json as? [String: Any], let name = jsonDict["name"] as? String else {
return nil
}
self.name = name
}
}
//Let's say you got a JSON array of User objects
let usersJSON: JSON
let users = [User](usersJSON)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment