Swift: Declare an Empty Dictionary

Swift: declare an empty dictionary

var emptyDictionary = [String: String]()


var populatedDictionary = ["key1": "value1", "key2": "value2"]

Note: if you're planning to change the contents of the dictionary over time then declare it as a variable (var). You can declare an empty dictionary as a constant (let) but it would be pointless if you have the intention of changing it because constant values can't be changed after initialization.

Different ways to declare a dictionary in Swift?]

They both do the same thing to declare and initialize an empty dictionary of that key and value type.

Apple documents the first way in their Swift Guide. (Scroll down to Dictionaries section).

The second way you show is simply more formal, which may help those new to Swift who don’t know the dictionary shorthand/literal syntax.

The

How to initialise an empty dictionary that contain objects in Swift

You didn't copy the syntax. ':' and '=' are not equivalent. In this case, one specifies a type while the other specifies initialization.

Try:

var menuItem = Dictionary<Int,MenuItem>()

Initiate empty Swift array of dictionaries

If we assume you try to initialize a array of dictionary with key String and value String you should:

var locations: [[String: String]] = []

then you could do:

locations.append(["location": "New York", "temp": "2 °C", "wind": "3 m/s"])

Making a Dictionary in Swift

I finally found it out how can i do it.

I use a struct with what I want like this:

var userDictionary = [Int : Event]()
struct Event {
var nameEvent: String
var nameMagazi: String

}

And then i use this:

  if let objects = objects  {
for object in objects {

let post = object["idEvent"] as? PFObject
let post2 = post!["idMagazi"] as? PFObject

let nameEvent = post!["name"] as! String
let idEvent = post?.objectId
let nameMagazi = post2!["name"] as! String

self.events[self.i] = Event(nameEvent: nameEvent , nameMagazi: nameMagazi)

self.i += 1
}
print(self.events[1]!.nameEvent)
}

Thank you all for your answers!

Initialising empty arrays of dictionaries in Swift

You need to give types to the dictionaries:

var myNewDictArray: [Dictionary<String, Int>] = []

or

var myNewDictArray = [Dictionary<String, Int>]()

Edit: You can also use the shorter syntax:

var myNewDictArray: [[String:Int]] = []

or

var myNewDictArray = [[String:Int]]()


Related Topics



Leave a reply



Submit