Dictionary 按键的字典值
在尝试从Dictionary 按键的字典值,dictionary,key,swift,subscript,Dictionary,Key,Swift,Subscript,在尝试从字典中获取值时,Xcode向我显示以下错误: 找不到接受提供的参数的“subscript”的重载 class func fromDictionary(enterpriseDictionary:Dictionary)->Enterprise { var-enterprise:enterprise=enterprise() enterprise.id=enterpriseDictionary[“id”]作为Int(此处出错) enterprise.name=enterpriseDiction
字典中获取值时,Xcode向我显示以下错误:
找不到接受提供的参数的“subscript”的重载
class func fromDictionary(enterpriseDictionary:Dictionary)->Enterprise
{
var-enterprise:enterprise=enterprise()
enterprise.id=enterpriseDictionary[“id”]作为Int(此处出错)
enterprise.name=enterpriseDictionary[“name”]作为?字符串(和此处)
退货企业
}
我设法解决了这个问题,将“AnyObject”替换为“Any”,如下所示:
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
}
class func fromDictionary(enterpriseDictionary:Dictionary)->Enterprise
{
var-enterprise:enterprise=enterprise()
enterprise.id=enterpriseDictionary[“id”]作为Int
enterprise.name=enterpriseDictionary[“name”]作为?字符串
退货企业
}
正如@Andrey Tarantsov所说:
这是因为AnyObject用于任何类实例(您也可以将其视为Objective-C意义上的对象);String和Int不是类。你能显示调用代码吗?是的,我想Int
和String
不是对象,所以Any
就是你想要的。你不能将一个对象向下转换为一个基元类型,编译器可以在一英里之外看到它;String和Int不是类。
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
}