【问题标题】:How to avoid force downcasting and unwrapping optionals without nested loops in Swift?如何避免在 Swift 中没有嵌套循环的情况下强制向下转换和展开选项?
【发布时间】: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


【解决方案1】:

你也可以这样写:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 2020-11-25
    • 2014-01-06
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多