我已经在其他问题中看到了这个问题的解决 - 但我认为因为这个 NSDictionary 是通过下标访问的,所以它会抛出一些错误。
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]
类型,你必须制作一个单独的字典:
var dict = [String : Any]()
for (key, value) in randomRecipe {
dict[key] = value
}
关于ios - 将 NSDictionary 转换为字典 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765875/