ios - 将 NSDictionary 转换为字典 Swift

标签 ios swift dictionary casting subscript

我已经在其他问题中看到了这个问题的解决 - 但我认为因为这个 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/

相关文章:

python - 使用字典将 "sequential"信息添加到 python 列表

ios - 如何在 iOS 网络接入时自动与服务器同步?

ios - 尝试使用 URLsession 从 DataTask 创建图像无效

ios - "variable:Type"和 "variable as Type"swift 有什么区别

python - swift中类似python的map函数

c# - 如果字典没有被修改,Dictionary.Keys顺序保证是相同的吗?

ios - 使用 switch/case 和通过数组填充的组 tableView

ios - 呈现 modalViewController 正在释放调用它的那个

ios - 无法通过 UIView 通过 swift 创建 pdf?

ios - 按下按钮时更改文本颜色?