-2

I'm having a difficult time trying not to write nested loops whenever I avoid force downcasting and unwrapping optionals. Is there a way to do this?

Example:

var customers = [Customer]()
if response.result.isSuccess, let jsonDictionary = response.result.value as? NSDictionary {
    if let usersJSON = jsonDictionary.object(forKey: "users") as? [NSDictionary] {
        for customerJSON in usersJSON {
            if let customer = Customer.from(customerJSON) {
                customers.append(customer)
            }
        }
    }
}

completionHandler(customers)
kevinnguy
  • 454
  • 4
  • 13
  • Where are you using nested loops? There are no nested loops in the code you posted. – rmaddy Apr 13 '17 at 22:23
  • 1
    And this is Swift. Why are you using `NSDictionary` instead of a Swift dictionary? – rmaddy Apr 13 '17 at 22:24
  • Btw, if you really experiencing pain in parsing JSON, i would recommend looking into what this library does https://github.com/JohnSundell/Unbox – Zapko Apr 13 '17 at 22:25

1 Answers1

0

You can also write like this:

guard response.result.isSuccess, 
   let jsonDictionary = response.result.value as? NSDictionary,
   let usersJSON = jsonDictionary.object(forKey: "users") as? [NSDictionary] else { completionHandler([]) }

completionHandler(usersJSON.flatMap(Customer.from))
Zapko
  • 2,461
  • 25
  • 30