Last active
January 24, 2017 09:59
-
-
Save marinbenc/36be816f7b100a8fa7ccc15d329f4db0 to your computer and use it in GitHub Desktop.
Make a Swift Array conform to Decodable (for JSON parsing)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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