declare array of dictionaries with fixed keys

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 ? 🙂

Accepted Reply

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 ?

Replies

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 ?

Exactly , gentle 😁

Thank you !

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: "****",  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"