将 NSDictionary 转换为字典 Swift
Casting NSDictionary as Dictionary 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
}
NSDictionary 应该桥接到 [NSCopying: AnyObject]
或者在你的情况下 [String: AnyObject]
,而不是使用 Any
(因为那是一个 Swift-only 构造)。
但我建议完全不要使用 NSDictionary。您可以将函数定义为
typealias Recipe = [String: AnyObject] // or some other Recipe class
func pickRandomRecipe(recipes: [Recipe]) -> Recipe? {
if recipes.isEmpty { return nil }
let index = Int(arc4random_uniform(UInt32(recipes.count)))
return recipes[index]
}
或者甚至更好:
extension Array {
func randomChoice() -> Element? {
if isEmpty { return nil }
return self[Int(arc4random_uniform(UInt32(count)))]
}
}
if let recipe = recipes.randomChoice() {
// ...
}
在这种情况下 NSDictionary
只能转换为 [String: NSObject]
。如果你希望它是 [String : Any]
类型,你必须制作一个单独的字典:
var dict = [String : Any]()
for (key, value) in randomRecipe {
dict[key] = value
}
我在其他问题中看到了这个问题的解决 - 但我认为因为这个 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 应该桥接到 [NSCopying: AnyObject]
或者在你的情况下 [String: AnyObject]
,而不是使用 Any
(因为那是一个 Swift-only 构造)。
但我建议完全不要使用 NSDictionary。您可以将函数定义为
typealias Recipe = [String: AnyObject] // or some other Recipe class
func pickRandomRecipe(recipes: [Recipe]) -> Recipe? {
if recipes.isEmpty { return nil }
let index = Int(arc4random_uniform(UInt32(recipes.count)))
return recipes[index]
}
或者甚至更好:
extension Array {
func randomChoice() -> Element? {
if isEmpty { return nil }
return self[Int(arc4random_uniform(UInt32(count)))]
}
}
if let recipe = recipes.randomChoice() {
// ...
}
在这种情况下 NSDictionary
只能转换为 [String: NSObject]
。如果你希望它是 [String : Any]
类型,你必须制作一个单独的字典:
var dict = [String : Any]()
for (key, value) in randomRecipe {
dict[key] = value
}