【发布时间】:2017-04-13 22:07:57
【问题描述】:
每当我避免强制向下转换和展开可选选项时,我都很难尝试不编写嵌套循环。有没有办法做到这一点?
例子:
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)
【问题讨论】:
-
你在哪里使用嵌套循环?您发布的代码中没有嵌套循环。
-
这是斯威夫特。你为什么使用
NSDictionary而不是 Swift 字典? -
顺便说一句,如果你在解析 JSON 时真的很痛苦,我建议你看看这个库做了什么github.com/JohnSundell/Unbox
标签: swift downcast forced-unwrapping