混淆语法!此代码中的运算符

问题描述 投票:0回答:1

我有一个发帖请求。我正在使用存储在obj中的响应。在顶部var account = Account()声明以下内容,其中Account()是字典初始化的类。

var obj = response.result.value as? [String: Any]

            if response.response?.statusCode == 200 {
                let accounts = obj!["accounts"] as! [[String: Any]]
                accounts.forEach { a in
                    let acc = Account(dic: a)
                    self.account = acc
                }
            }

我对目前尚不了解的语法感到非常困惑:let accounts = obj!["accounts"] as! [[String: Any]]

我只知道这使我可以将响应存储到self.account中,然后可以使用该数据填充我的视图。有人可以帮忙详细说明这里到底发生了什么吗?

谢谢。

swift dictionary structure
1个回答
0
投票
let accounts = obj!["accounts"] as! [[String: Any]]

让我们将该行分解为较小的“块”:

obj! // Force unwraps the object "obj" (which is a dictionary) (will crash if "obj" is nil
obj!["accounts"] // After being unwrapped tries to access the key "accounts" inside the dictionary
as! [[String: Any]]// Is going to "cast" or treat the above dictionary as an Array of Dictionaries of String: Any (again forcing it and crash if it cannot)

但请记住!

强制解开包装不是很好的做法,因为您的应用可能会崩溃。您应该始终选择可选的绑定或可选的链接。

© www.soinside.com 2019 - 2024. All rights reserved.