Chr*_*ris 2 dictionary casting subscript ios swift
我已经看到这在其他问题中得到了解决 - 但我认为因为这个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
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下NSDictionary只能铸造[String: NSObject].如果你想要它的类型,[String : Any]你必须创建一个单独的词典:
var dict = [String : Any]()
for (key, value) in randomRecipe {
dict[key] = value
}
Run Code Online (Sandbox Code Playgroud)