Casting NSDictionary as Dictionary Swift

本小妞迷上赌 提交于 2019-12-11 00:09:44

问题


I've seen this solved in other questions - but I think that because this NSDictionary is accessed via subscript it's throwing some errors.

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
}

回答1:


In this case NSDictionary can only be casted to [String: NSObject]. If you want it to be of type [String : Any] you have to make a separate Dictionary:

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



回答2:


NSDictionary should be bridged to [NSCopying: AnyObject] or in your case [String: AnyObject], rather than using Any (since that's a Swift-only construct).

But I would recommend not using NSDictionary at all. You could define your function as

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]
}

Or perhaps even better:

extension Array {
    func randomChoice() -> Element? {
        if isEmpty { return nil }
        return self[Int(arc4random_uniform(UInt32(count)))]
    }
}

if let recipe = recipes.randomChoice() {
    // ...
}


来源:https://stackoverflow.com/questions/31765875/casting-nsdictionary-as-dictionary-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!