Skip to content

Instantly share code, notes, and snippets.

@mxcl
Forked from hartbit/PromiseKit + YOLO?
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxcl/4bcd7966d1fd8c4fc79b to your computer and use it in GitHub Desktop.
Save mxcl/4bcd7966d1fd8c4fc79b to your computer and use it in GitHub Desktop.
// Trying to write a function that does some select/map magic with easy error handling
let cities = [[
"name": "Geneva",
"population": 184538
],[
"name": "Bern",
"population": 123154
], [
"name": "Zurich",
"population": 366765
], [
"name": "Rubish",
"population": -500
]]
struct City {
let name: String
let population: Int
init?(name: String, population: Int) {
if population > 0 {
self.name = name
self.population = population
} else {
return nil
}
}
}
// 1. No error handling
// -> Easy but crash prone
func citiesFromJSON(json: [[String:Any]]) -> [City] {
return json.map({ (dictionary: [String:Any]) -> City in
return City(name: dictionary["name"] as String, population: dictionary["population"] as Int)!
})
}
// 2. for loop NSError solution
// -> Crash resistent but not very functional
func citiesFromJSON(json: [[String:Any]], error: NSErrorPointer) -> [City] {
var cities: [City] = []
for dictionary in json {
if let name = dictionary["name"] as? String {
if let population = dictionary["population"] as? Int {
if let city = City(name: name, population: population) {
cities.append(city)
continue
}
}
}
error.memory = NSError(domain: "domain", code: 666, userInfo: nil)
return []
}
return cities
}
func citiesFromJSON(json: [[String:Any]]) -> Promise<[City]> {
return Promise{ fulfill, reject in
fulfill(json.map{ dictionary in
if let name = dictionary["name"] as? String {
if let population = dictionary["population"] as? Int {
if let city = City(name: name, population: population) {
return city
}
}
}
reject(NSError(domain: "domain", code: 666, userInfo: nil))
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment