无法将字典值转换为Array <string> </string>

时间:2014-07-24 19:53:25

标签: ios7 swift ios8 xcode6

var mContent: Dictionary<String, Dictionary<String, AnyObject>>;
...
let lContent = mContent["tabbar"] as Dictionary<String, AnyObject>;
let lTabBarItemsTitles = lContent["itemTitles"] as Array<String>;

Xcode在第二行显示编译错误,告诉:'String' is not convertible to Dictionary<String, AnyObject>

lContent["itemTitles"]Array<String>。为什么Xcode会显示此错误以及如何从Array获取Dictionary

1 个答案:

答案 0 :(得分:1)

这是因为subscript中的Dictionary会返回一个可选项:

subscript (key: KeyType) -> ValueType?

这意味着你必须先打开可选项才能进行向下转换:

let lContent = mContent["tabbar"]! as Dictionary<String, AnyObject>
let lTabBarItemsTitles = lContent["itemTitles"]! as Array<String>

从Beta 3开始,您可以直接访问该值而无需向下转换,如下所示:

let lContent = mContent["tabbar"]!
let lTabBarItemsTitles = lContent["itemTitles"]

但是我建议你把它包裹在if-let周围,以确保你不会打开零值。