简体   繁体   中英

How to create and add values to Dictionary in swift

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

{
  "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

LangInfo Lang Info

EduInfo EduInfo

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.

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

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 )

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM