如何在Swift中避免使用嵌套循环强制向下转换和展开选项?

时间:2017-04-13 22:07:57

标签: swift downcast forced-unwrapping

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

示例:

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)

1 个答案:

答案 0 :(得分: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))