ios 如何快速创建和添加值到字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30739255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:18:06  来源:igfitidea点击:

How to create and add values to Dictionary in swift

iosswiftdictionary

提问by Varun Naharia

I want to create a Dictionary in swift with different type of data(array, string,dictionary)I am able to insert new data to a key but having difficulty in appending more values to them here is the json for the dictionary

我想用不同类型的数据(数组、字符串、字典)快速创建一个字典我能够将新数据插入到一个键中,但在向它们附加更多值时遇到困难,这里是字典的 json

{
  "GenInfo": {
    "First Name":"Varun",
    "Last Name":"Naharia",
    "Phone No":"123456789"
  },
  "LangInfo": ["Hindi","English","Urdu","French"],
  "EduInfo": 
    [
      {
        "Collage":"CIITM",
        "Year":"2009",
        "Degree":"BCA"
      },
      {
        "Collage":"Dept. Of Comp. Sci. & Infor. University Of Kota",
        "Year":"2013",
        "Degree":"MCA"
      }
    ]
}

I want to add these values to dictionary one by one like first GenInfo, then first language of LangInfo then EduInfo

我想将这些值一个一个地添加到字典中,例如第一个 GenInfo,然后是 LangInfo 的第一种语言,然后是 EduInfo

LangInfoLang Info

朗讯朗信息

EduInfoEduInfo

教育资讯教育资讯

I Used dict["GenInfo"] = ["FirstName":first,"LastName":last,"Phone":phone]to add the GenInfo in the dic where first and last is the variable with value.

我曾经dict["GenInfo"] = ["FirstName":first,"LastName":last,"Phone":phone]在 dic 中添加 GenInfo,其中 first 和 last 是带值的变量。

EDIT #1var dict = Dictionary<String, Any>()

编辑#1var dict = Dictionary<String, Any>()

采纳答案by Remy Cilia

This is a known issue, apparently not fixed yet (see Is it possible to have a dictionary with a mutable array as the value in Swift)

这是一个已知问题,显然尚未修复(请参阅是否可以将具有可变数组的字典作为 Swift 中的值

The workaround would be to create a new variable with your array and then assign it back:

解决方法是使用数组创建一个新变量,然后将其分配回:

    var dict = [String: AnyObject]()
    dict["GenInfo"] = ["FirstName":"first","LastName":"last","Phone":"phone"]
    dict["Language"] = ["langage1", "langage2"]

    if var languages = dict["Language"] as? [String] {
        languages.append("langage3")
        dict["Language"] = languages
    }