如何避免Swift中没有嵌套循环的强制向下投射和展开选项?
每当我避免强制向下投射和展开选项时,我都很难尝试不编写嵌套循环。有办法做到这一点吗 例如:如何避免Swift中没有嵌套循环的强制向下投射和展开选项?,swift,downcast,forced-unwrapping,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] {
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)
你也可以这样写:
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))
在哪里使用嵌套循环?您发布的代码中没有嵌套循环。这是Swift。为什么要使用NSDictionary而不是Swift字典?顺便说一句,如果您在解析JSON时真的遇到了麻烦,我建议您研究一下这个库的功能