-2

每当我避免强制向下转换和展开选项时,我都很难尝试不编写嵌套循环。有没有办法做到这一点?

例子:

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

1 回答 1

0

你也可以这样写:

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))
于 2017-04-13T22:16:19.393 回答