Dictionarys的Swift选项

时间:2016-03-29 14:34:01

标签: swift

MFSAPIManager().registerNewUser(userFirstName!, lastName: userLastName!, userTypeId: 1, email: userEmail!, password: userPassword!, completionHandler: { (response) in

        guard response.error == nil else {
            if let error = response.error {
                print(error)
            }
            dispatch_async(GlobalMainQueue) {
                self.displayAlertViewController(title: "Error", message: "Der Benutzer konnte nicht registriert werden")
            }
            return
        }

        if let serverResponse = response.value as? Dictionary<String,AnyObject> {
            let newUserReference = serverResponse["data"]!["userReference"]

            if (newUserReference != nil) {
                self.currentPLISTData["userReference"] = newUserReference
                dispatch_async(GlobalMainQueue) {
                    var myAlert = UIAlertController(title: "Alert", message: "Registrierung erfolgreich", preferredStyle: UIAlertControllerStyle.Alert)
                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) in
                        self.dismissViewControllerAnimated(true, completion: nil)
                    })
                    myAlert.addAction(okAction)
                    self.presentViewController(myAlert, animated: true, completion: nil)
                }
            }
        }


    })

我收到一条需要更改的错误消息:

let newUserReference = serverResponse["data"]["userReference"]

let newUserReference = serverResponse["data"]!["userReference"]

解开["data"]组件。我很困惑为什么会这样呢?

2 个答案:

答案 0 :(得分:4)

Swift词典总是返回一个Optional。

这意味着,为了能够使用serverResponse["data"]下标["userReference"],您首先需要解开serverResponse["data"]

可以不安全地完成,例如在您的示例中,或安全地使用if let之类的内容:

if let data = serverResponse["data"] {
    let newUserReference = data["userReference"]
}

另请注意,编译器现在可能不是serverResponse["data"]的类型,因此您可能需要向下转换它才能下标,例如:

if let data = serverResponse["data"] as? [String:AnyObject] {
    let newUserReference = data["userReference"]
}

答案 1 :(得分:1)

通过下标访问Dictionary<Key,Value>会返回Value?。这是因为您要查找的键值对可能不在字典中。因此,如果它找到键,则返回一个可选的set,如果它没有,则返回unset。

我会用这种方式处理它,使用可选的链接:

if let serverResponse = response.value as? Dictionary<String,AnyObject>,
       newUserReference = serverResponse["data"]?["userReference"] {
  ...
}

将所有if..let语句合并为一个,可以减少'pyramid of doom'

Eric D指出你应该测试第一个下标的类型,我会这样做:

if let serverResponse = response.value as? Dictionary<String,AnyObject>,
       data = serverResponse["data"] as? [String:AnyObject],
       newUserReference = data["userReference"] {
  ...
}