将NSDictionary转换为字典Swift [英] Casting NSDictionary as Dictionary Swift
本文介绍了将NSDictionary转换为字典Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到在其他问题中解决了这个问题 - 但是我认为这是因为这个NSDictionary是通过下标访问的,它会抛出一些错误。
I've seen this solved in other questions - but I think that because this NSDictionary is accessed via subscript it's throwing some errors.
func pickRandomRecipe(arrayOfRecipes: NSArray) -> Dictionary<String,Any> {
let randomRecipeIndex = Int(arc4random_uniform(UInt32(arrayOfRecipes.count)))
//Could not cast value of type '__NSDictionaryI' (0x7fbfc4ce0208) to 'Swift.Dictionary<Swift.String, protocol<>>' (0x7fbfc4e44358)
let randomRecipe: Dictionary = arrayOfRecipes[randomRecipeIndex] as! Dictionary<String,Any>
return randomRecipe
}
推荐答案
在这种情况下, NSDictionary
只能转换为 [String:NSObject]
。如果你想要它是类型 [String:Any]
,你必须制作一个单独的字典:
In this case NSDictionary
can only be casted to [String: NSObject]
. If you want it to be of type [String : Any]
you have to make a separate Dictionary:
var dict = [String : Any]()
for (key, value) in randomRecipe {
dict[key] = value
}
这篇关于将NSDictionary转换为字典Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文