Skip to content

Instantly share code, notes, and snippets.

@ghthor
Last active August 27, 2016 17:50
Show Gist options
  • Select an option

  • Save ghthor/85ced69441e4a0cabb9003379031bbd3 to your computer and use it in GitHub Desktop.

Select an option

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
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