3 Replies
      Latest reply: Oct 18, 2016 2:22 AM by eskimo RSS
      stcocoa Level 1 Level 1 (0 points)

        hI ,

         

        I just want to dictonary like this..

        ["name":"", "birthday":"", "gender":""]

         

         

        and I have many of that dictionary,   and that should be inclueded in one array.

         

        How can I declare it ?

        • Re: declare array of dictionaries with fixed keys
          Claude31 Level 4 Level 4 (825 points)

          write :

           

          var myDict1 : [String:String] = ["name":"", "birthday":"", "gender":""]
          

           

          then you will populate with :

           

          myDict1["name"] = "myName"
          

           

          to put in an array :

           

          var myArrayOfDict : Array< [String:String]>
          var myDict1 : [String:String] = ["name":"", "birthday":"", "gender":""]
          myArrayOfDict.append(myDict1)          // And so on for the others indexes
          

           

          then you will populate with :

           

          myArrayOfDict[0]["name"] = "myName"
          

           

          Is it what you're looking for ?

          • Re: declare array of dictionaries with fixed keys
            eskimo Apple Staff Apple Staff (6,310 points)

            Claude31’s answer is correct but IMO you’d be better off doing this with a struct.

            struct Person {
                var name: String = ""
                var birthday: String = ""
                var gender: String = ""
            }
            
            let d = [
                Person(name: "Tom",  birthday: "yesterday", gender: "n/a"),
                Person(name: "Dick",  birthday: "today",    gender: "n/a"),
                Person(name: "Harry", birthday: "tomorrow",  gender: "n/a"),
            ]
            

            Arrays of dictionaries have their place but if you can use a strong type you’ll benefit from that down the path.  For example, to get a list of names with this code you’d write:

            let names = d.map { $0.name }
            

            Doing this with dictionary-based code would require:

            let names = d.map { $0["name"]! }
            

            which needs a forced unwrap because Swift doesn’t know that the dictionary always contains a name.

            Taking this a step further I’d probably store the birthday in a DateComponents and define an enum for the gender.  This might sound like a bunch of up front work but it will make the code that consumes this data structure both easier to write and safer.

            Share and Enjoy

            Quinn “The Eskimo!”
            Apple Developer Relations, Developer Technical Support, Core OS/Hardware
            let myEmail = "eskimo" + "1" + "@apple.com"