Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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