铸造NSDictionary作为词典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只能被转换为[String: NSObject] 。 如果你想要它的types[String : Any]你必须做一个单独的字典:

 var dict = [String : Any]() for (key, value) in randomRecipe { dict[key] = value } 

NSDictionary应该桥接到[NSCopying: AnyObject]或在你的情况[String: AnyObject] ,而不是使用Any (因为这是一个Swift只)构造。

但我会build议不要使用 NSDictionary。 你可以定义你的function

 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() { // ... }