NSMutableDictionary:转换为无关的Swift类型?

时间:2015-09-14 12:46:26

标签: swift dictionary casting nsmutabledictionary

任何人都可以帮助我解决这个问题的正确方法,我尝试了各种版本,但总是遇到错误或警告。下面的代码和输出来自Swift Playground。

var foundationDict = NSMutableDictionary()
foundationDict.setObject("Bilbo", forKey: "FirstName")
foundationDict.setObject("Baggins", forKey: "LastName")

var swiftDict = foundationDict as! Dictionary<String, String>
for (key, value) in swiftDict {
    print("KEY: \(key) VALUE: |\(value)")
}

输出:

KEY: FirstName VALUE: |Bilbo
KEY: LastName VALUE: |Baggins

警告:

Cast from NSMutableDictionary to unrelated type Dictionary<String String> always fails

3 个答案:

答案 0 :(得分:5)

我不确定为什么,但是这样用语法来消除警告:

var swiftDict = (foundationDict as NSDictionary) as! Dictionary<String, String>

在这种情况下,类型系统似乎很难使用NSMutableDictionary / NSDictionary。

答案 1 :(得分:2)

您的代码的正确版本是:

var foundationDict = NSMutableDictionary()
foundationDict.setObject("Bilbo", forKey: "FirstName")
foundationDict.setObject("Baggins", forKey: "LastName")

for (key, value) in foundationDict {
   println("KEY: \(key) VALUE: |\(value)")
}

没有必要进行转换,因为NSDictionary被桥接到swift Dictionary并且foundationDict现在是一个快速的mutableDict。

答案 2 :(得分:2)

没有警告你可以按照这种方式

var addressDict = NSMutableDictionary()
addressDict["key"] = "value"

if let dict = (addressDict as NSDictionary) as? [String:AnyObject]  {
    print(dict) 
}