字典值按键

时间:2014-06-03 22:26:44

标签: dictionary key swift subscript

在尝试从Dictionary获取值时,Xcode向我显示以下错误:

  

找不到'下标'的重载接受提供的参数

class func fromDictionary(enterpriseDictionary:Dictionary<String, AnyObject>) -> Enterprise
{
    var enterprise:Enterprise = Enterprise()

    enterprise.id = enterpriseDictionary["id"] as Int  (ERROR OCCURS HERE)
    enterprise.name = enterpriseDictionary["name"] as? String ( AND HERE )


    return enterprise
}

1 个答案:

答案 0 :(得分:0)

我设法通过替换&#34; AnyObject&#34;来解决这个问题。 by&#34; Any&#34;如下所示:

class func fromDictionary(enterpriseDictionary:Dictionary<String, Any>) -> Enterprise
{
    var enterprise:Enterprise = Enterprise()

    enterprise.id = enterpriseDictionary["id"] as Int
    enterprise.name = enterpriseDictionary["name"] as? String


    return enterprise
}

正如@Andrey Tarantsov所说:

这是因为AnyObject适用于任何类实例(您也可以将其视为Objective-C意义上的对象); String和Int不是类。