Casting NSDictionary as a Swift Dictionary

I saw this in other questions, but I think that since this NSDictionary is accessible through an index, it throws 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
}
+2
source share
2 answers

In this case, NSDictionarycan only be sent to [String: NSObject]. If you want this to be of type [String : Any], you need to make a separate dictionary:

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

NSDictionary should be bound to [NSCopying: AnyObject]or in your case [String: AnyObject], and not used Any(since this is just a Swift construct).

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

Source: https://habr.com/ru/post/1659505/


All Articles