sourceplaze
sourceplaze

Reputation: 333

How to properly use dictionary collection?

Here is my code:

class className: Codable {
    let comments: [String: String, String:String]
}

I am getting the following errors:

Expected ']' in dictionary type

Expected declaration

Consecutive declarations on a line muse be separated by ';'

From Swift docs it is done this way (I think):

let comments: [String: String]

But for me it won't work because my comments in mongoose.Schema is defined as below (in the server):

comments: [{
    identifier: String,
    text: String
}]

I defined comments collection to push it to the server for testing as below (it worked):

var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"]

Now my question is, how can I define the comments in my class that extends Codable to match my comments in the server?

Upvotes: 0

Views: 49

Answers (2)

David Pasztor
David Pasztor

Reputation: 54745

let comments: [String: String] is the correct way.

You want a Dictionary, whose keys are Strings and whose values are also Strings and that's what the above line declares.

If you check the type of your comments variable when declaring it with initial values (option click on the variable name), you'll see that its type is [String:String], which is just a shorthand notation for Dictionary<String,String>.

var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"] //Here comments is of type [String:String]

Upvotes: 1

David Vicente
David Vicente

Reputation: 3121

It should be an array of documents, so probably something like this should work:

class className: Codable {
    let comments: [{String: String, String:String}]
}

And the collection for testing the same:

var comments = [{"identifier" : "SomeRandomText", "text": "SomeRandomText"}]

Upvotes: 0

Related Questions