Last active
August 27, 2016 17:50
-
-
Save ghthor/85ced69441e4a0cabb9003379031bbd3 to your computer and use it in GitHub Desktop.
An example of using flatMap to extract fields from a [String: AnyObject] dictionary into a concrete type
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
| import Foundation | |
| func toString(obj: AnyObject) -> String? { | |
| return obj as? String | |
| } | |
| func toJSON(obj: AnyObject) -> [String: AnyObject]? { | |
| return obj as? [String: AnyObject] | |
| } | |
| func toInt(obj: AnyObject) -> Int? { | |
| return obj as Int | |
| } | |
| func toJSONArray(obj: AnyObject) -> [[String: AnyObject]]? { | |
| return obj as? [[String: AnyObject]] | |
| } | |
| struct Person { | |
| struct Name { | |
| let first: String | |
| let last: String | |
| } | |
| let id: Int | |
| let name: Name | |
| } | |
| func toName(obj: [String: AnyObject]) throws -> Name { | |
| guard let first = obj["first"]?.flatMap(toString) else { | |
| throw "unsupported structure" | |
| } | |
| guard let last = obj["last"]?.flatMap(toString) else { | |
| throw "unsupported structure" | |
| } | |
| return Name(first: first, last: last) | |
| } | |
| let jsonStr = "{\"people\":[{\"id\":0, \"name\":{\"first\":\"taco\",\"last\":\"dog\"}}]}" | |
| let JSON: [String: AnyObject] | |
| do { | |
| JSON = try NSJSONSerialization.JSONObjectWithData(jsonStr.dataUsingEncoding(NSUTF8StringEncoding), options: nil) | |
| } catch(let error) { | |
| print(error) | |
| JSON = [:] | |
| } | |
| let people = JSON["people"].flatMap(toJSONArray).flatMap { JSON -> [People] in | |
| do { | |
| let name = try JSON["name"].flatMap(toName) | |
| return [Person(id: JSON["id"].flatMap(toInt) ?? -1, name: name)] | |
| } catch (let error) { | |
| print(error) | |
| return [] | |
| } | |
| } ?? [] | |
| print(people) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment