有人可以帮助我吗?从现在开始,从来没有机会在Swift中管理字典.解决方案如果您可以使用key"FD",它将更加简单dictionaries["FD"]!["TT"] = 6添加新值["TT":6]或将TT的现有值修改为6.请注意!在["FD"]之间!["TT"]假定["FD"]存在.否则,您需要检查["FD"]是否存在.喜欢:if dictionaries["FD"] != nil { dictionaries["FD"]!["TT"] = 6} else { dictionaries["FD"] = ["TT" : 6]}如果需要查找key,则必须像您已经尝试过的那样运行整个字典,但是字典支持对键和值(如)的快速枚举.for (key,value) in dictionaries { if key.contains("FD") { //or any other checks you need to identify your key value["TT"] = 6 }}I have this structure: [String: [String: Double]]()Specifically, something like that: var dictionaries = ["GF": ["ET": 4.62, "EO": 21.0],"FD": ["EE": 80.95, "DE": 0.4]]How can I easily access and modify nested dictionaries?EXAMPLE UPDATED: I want to append "TT": 6 at FD and later I want to append another dictionary inside the array. At the end I'll print the results.for (key,value) in dictionaries { // if array contains FD, add the record to FD if key.contains("FD") { dictionaries["FD"]!["TT"] = 6 } else { // if array doesn't contain FD, add FD and add the record to it dictionaries = dictionaries+["FD"]["TT"] = 6 // <-- I know that it's wrong but I want to achieve this result in this case. }}Result of print will be: GF -> ET - 4.62, EO - 21.0FD -> EE - 80.95, DE - 0.4, TT - 6MISSION: I need to append new dictionary records like in the example above, update existing ones in a simple and straightforward way, loop easily through records to read the values and print them out.Can anyone help me? Never had the chance to manage dictionaries in Swift since now. 解决方案 It'll be much simpler if you have the key "FD" you can usedictionaries["FD"]!["TT"] = 6to add a new value ["TT":6] or modify existing value of TT to 6. Note that the ! between ["FD"]!["TT"] assumes that ["FD"] exists regardless. You need to check if ["FD"] exists otherwise. Like:if dictionaries["FD"] != nil { dictionaries["FD"]!["TT"] = 6} else { dictionaries["FD"] = ["TT" : 6]}If you need to look for the key you will have to run the entire dictionary like you already tried, but dictionaries support fast enumeration for key and values likefor (key,value) in dictionaries { if key.contains("FD") { //or any other checks you need to identify your key value["TT"] = 6 }} 这篇关于在Swift中轻松访问和修改字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-23 22:06