Xcode 6:Postfix的操作数"!"应该有可选的类型

时间:2014-09-05 02:18:30

标签: xcode swift

运行Xcode 6 Beta 7,

我正在尝试打开一个名为detail的词典,其中包含一个categories字典数组category。每个category都是[String : AnyObject]

类型
var category: [String: AnyObject] = detail!["categories"]![categoryIndex] as [String: AnyObject]

我收到错误

Operand of Postfix "!" should have optional type, type is '(String, AnyObject)'

如果我删除感叹号“!”正如编译器建议的那样

var category: [String: AnyObject] = detail!["categories"][categoryIndex] as [String: AnyObject]

我收到错误

(String, AnyObject) does not have the member named `subscript`

帮助!

这是我的detail声明

var detail: [String : AnyObject]?

1 个答案:

答案 0 :(得分:3)

问题似乎是编译器在访问它们时无法弄清楚如何转换各种AnyObject。您可以使用一些创意内联强制转换来解决它:

var category: [String: AnyObject]? = ((detail?["categories"] as AnyObject?) as? [[String: AnyObject]])?[categoryIndex]

将这些步骤分开会更好:

var categoriesObj: AnyObject? = detail?["categories"]
var categories: [[String: AnyObject]]? = categoriesObj as? [[String: AnyObject]]
var category: [String: AnyObject]? = categories?[categoryIndex]

注意:我必须将 category 更改为 [String: AnyObject]?