Swift: 无法下标 'Dictionary<String, NSObject>?' 类型的值

Swift: Cannot subscript a value of type 'Dictionary<String, NSObject>?'

编辑:不是重复的:

该解决方案给出 'Could not find an overload for 'subscript' that accepts the supplied arguments' 错误。所以,不,这不是重复的。

这是函数声明。

        func auth(user: String, pass: String, completion: (returned: Bool, error: Bool, response: Dictionary<String, NSObject>?) -> ()){

response 可以为零 }

现在我试图访问在另一个文件中传回的值并收到错误:

        if let labelString = response["error_description"] as! String?{
            self.labelPrompt.text = labelString
        }

错误: 无法使用 'String'

类型的索引为类型 'Dictionary?' 的值下标

链接问题的副本:你需要的是在使用下标之前打开字典。

有很多方法("if let" 等),链接的答案给出了使用 "optional binding" 的解决方案,方法是在保存字典的变量和下标之间添加 ?

游乐场中的示例:

var response: Dictionary<String, NSObject>? = nil

// NOTICE THE "?" BETWEEN THE VARIABLE AND THE SUBSCRIPT

if let labelString = response?["error_description"] as? String {
    println(labelString)  // not executed because value for key is nil
}

response = ["test":"yep"]

if let labelString = response?["test"] as? String {
    println(labelString)  // "yep"
}

另一种解包字典的方法:

if let responseOK = response, let test = responseOK["test"] as? String {
    println(test) // "yep"
}