每当我避免强制向下转换和展开选项时,我都很难尝试不编写嵌套循环。有没有办法做到这一点?
示例:
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)
答案 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))