Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何避免Swift中没有嵌套循环的强制向下投射和展开选项?_Swift_Downcast_Forced Unwrapping - Fatal编程技术网

如何避免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时真的遇到了麻烦,我建议您研究一下这个库的功能