如何在 Swift 中访问深度嵌套的字典 [英] How to access deeply nested dictionaries in Swift

查看:32
本文介绍了如何在 Swift 中访问深度嵌套的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个非常复杂的数据结构,我需要对其进行操作.我试图跟踪玩家在他们的花园中有多少种虫子.虫子有十种,每种有十种花纹,每种花纹有十种颜色.所以可能有 1000 个独特的错误,我想跟踪玩家有多少这些类型.嵌套字典看起来像:

I have a pretty complex data structure in my app, which I need to manipulate. I am trying to keep track of how many types of bugs a player has in thier garden. There are ten types of bugs, each with ten patterns, each pattern having ten colors. So there are 1000 unique bugs possible, and I want to track how many of each of these types the player has. The nested dictionary looks like:

var colorsDict: [String : Int]
var patternsDict: [String : Any] // [String : colorsDict]
var bugsDict: [String : Any] // [String : patternsDict]

我没有收到任何关于此语法的错误或投诉.

I do not get any errors or complaints with this syntax.

当我想增加玩家的错误收集时,这样做:

When I want to increment the player's bug collection though, doing this:

bugs["ladybug"]["spotted"]["red"]++

我收到此错误:String 不可转换为 'DictionaryIndex<;字符串,任何 >',在第一个字符串下带有错误的胡萝卜.

I get this error: String is not convertible to 'DictionaryIndex< String, Any >' with the error's carrot under the first string.

另一个类似的帖子建议使用as Any?"在代码中,但那篇文章的 OP 只有一个深度的字典,所以可以很容易地做到这一点: dict["string"] as Any?...

Another similar post suggested using "as Any?" in the code, but the OP of that post only had a dictionary one deep so could do that easily with: dict["string"] as Any? ...

我不确定如何使用多级字典来做到这一点.任何帮助将不胜感激.

I am not sure how to do this with a multilevel dictionary. Any help would be appreciated.

推荐答案

在使用字典时,您必须记住字典中可能不存在某个键.出于这个原因,字典总是返回可选项.因此,每次通过键访问字典时,您都必须按如下方式在每个级别解包:

When working with dictionaries you have to remember that a key might not exist in the dictionary. For this reason, dictionaries always return optionals. So each time you access the dictionary by key you have to unwrap at each level as follows:

bugsDict["ladybug"]!["spotted"]!["red"]!++

我想你知道可选项,但为了清楚起见,如果你 100% 确定键存在于字典中,请使用感叹号,否则最好使用问号:

I presume you know about optionals, but just to be clear, use the exclamation mark if you are 100% sure the key exists in the dictionary, otherwise it's better to use the question mark:

bugsDict["ladybug"]?["spotted"]?["red"]?++

附录:这是我在操场上测试时使用的代码:

Addendum: This is the code I used for testing in playground:

var colorsDict = [String : Int]()
var patternsDict =  [String : [String : Int]] ()
var bugsDict = [String : [String : [String : Int]]] ()

colorsDict["red"] = 1
patternsDict["spotted"] = colorsDict
bugsDict["ladybug"] = patternsDict


bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 1
bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 2
bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 3
bugsDict["ladybug"]!["spotted"]!["red"]! // Prints 4

这篇关于如何在 Swift 中访问深度嵌套的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆