Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>()

like image 280
Varun Naharia Avatar asked Jun 09 '15 17:06

Varun Naharia


People also ask

What are dictionaries in Swift?

Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.


1 Answers

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
    }
like image 130
Remy Cilia Avatar answered Nov 15 '22 20:11

Remy Cilia