将NSDictionary转换为字典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
}