[ios] Swift: declare an empty dictionary

I am beginning to learn swift by following the iBook-The Swift Programming Language on Swift provided by Apple. The book says to create an empty dictionary one should use [:] same as while declaring array as []:

I declared an empty array as follows :

let emptyArr = [] // or String[]()

But on declaring empty dictionary, I get syntax error:

let emptyDict = [:]

How do I declare an empty dictionary?

This question is related to ios swift dictionary

The answer is


var parking = [Dictionary < String, Double >()]

^ this adds a dictionary for a [string:double] input


You can declare it as nil with the following:

var assoc : [String:String]

Then nice thing is you've already typeset (notice I used var and not let, think of these as mutable and immutable). Then you can fill it later:

assoc = ["key1" : "things", "key2" : "stuff"]

It is very handy for finding your way

var dict:Dictionary = [:]


Use this will work.

var emptyDict = [String: String]()

You have to give the dictionary a type

// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()

If the compiler can infer the type, you can use the shorter syntax

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String

I'm playing with this too. It seems strange that you can just declare an empty dictionary and then add a key/value pair to it like so :

var emptyDictionary = Dictionary<String, Float>()
var flexDictionary = [:]
emptyDictionary["brian"] = 4.5
flexDictionary["key"] = "value" // ERROR : cannot assign to the result of this expression

But you can create a Dictionary that accepts different value types by using the "Any" type like so :

var emptyDictionary = Dictionary<String, Any>()
emptyDictionary["brian"] = 4.5
emptyDictionary["mike"] = "hello"

If you want to create a generic dictionary with any type

var dictionaryData = [AnyHashable:Any]()

You can't use [:] unless type information is available.

You need to provide it explicitly in this case:

var dict = Dictionary<String, String>()

var means it's mutable, so you can add entries to it. Conversely, if you make it a let then you cannot further modify it (let means constant).

You can use the [:] shorthand notation if the type information can be inferred, for instance

var dict = ["key": "value"]

// stuff

dict = [:] // ok, I'm done with it

In the last example the dictionary is known to have a type Dictionary<String, String> by the first line. Note that you didn't have to specify it explicitly, but it has been inferred.


You need to explicitly tell the data type or the type can be inferred when you declare anything in Swift.

Swift 3

The sample below declare a dictionary with key as a Int type and the value as a String type.

Method 1: Initializer

let dic = Dictionary<Int, String>()

Method 2: Shorthand Syntax

let dic = [Int:String]()

Method 3: Dictionary Literal

var dic = [1: "Sample"]
// dic has NOT to be a constant
dic.removeAll()

You can simply declare it like this:

var emptyDict:NSMutableDictionary = [:]

Swift:

var myDictionary = Dictionary<String, AnyObject>()

Swift 4

let dicc = NSDictionary()

//MARK: - This is empty dictionary
let dic = ["":""]

//MARK:- This is variable dic means if you want to put variable 
let dic2 = ["":"", "":"", "":""]

//MARK:- Variable example
let dic3 = ["name":"Shakeel Ahmed", "imageurl":"https://abc?abc.abc/etc", "address":"Rawalpindi Pakistan"]

//MARK: - This is 2nd Variable Example dictionary
let dic4 = ["name": variablename, "city": variablecity, "zip": variablezip]

//MARK:- Dictionary String with Any Object
var dic5a = [String: String]()
//MARK:- Put values in dic
var dic5a = ["key1": "value", "key2":"value2", "key3":"value3"]

var dic5b = [String:AnyObject]()
dic5b = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]

or
//MARK:- Dictionary String with Any Object
let dic5 = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]

//MARK:- More Easy Way
let dic6a = NSDictionary()
let dic6b = NSMutalbeDictionary()

I'm usually using

var dictionary:[String:String] = [:]
dictionary.removeAll()

var dictList = String:String for dictionary in swift var arrSectionTitle = String for array in swift


You can use the following code:

var d1 = Dictionary<Int, Int>()
var d2 = [Int: Int]()
var d3: Dictionary<Int, Int> = [Int : Int]()
var d4: [Int : Int] = [:]

Declaring & Initializing Dictionaries in Swift

Dictionary of String

var stringDict: [String: String] = [String: String]()

OR

var stringDict: Dictionary<String, String> = Dictionary<String, String>()

Dictionary of Int

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

OR

var stringDict: Dictionary<String, Int> = Dictionary<String, Int>()

Dictionary of AnyObject

var stringDict: [String: AnyObject] = [String: AnyObject]()

OR

var stringDict: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()

Dictionary of Array of String

var stringDict: [String: [String]] = [String: [String]]()

OR

var stringDict: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()

Array of Dictionaries of String

var stringDict: [[String: String]] = [[String: String]]()

OR

var stringDict: Array<Dictionary<String, String>> = Array<Dictionary<String, String>>()

The Swift documentation recommends the following way to initialize an empty Dictionary:

var emptyDict = [String: String]()

I was a little confused when I first came across this question because different answers showed different ways to initialize an empty Dictionary. It turns out that there are actually a lot of ways you can do it, though some are a little redundant or overly verbose given Swift's ability to infer the type.

var emptyDict = [String: String]()
var emptyDict = Dictionary<String, String>()
var emptyDict: [String: String] = [:]
var emptyDict: [String: String] = [String: String]()
var emptyDict: [String: String] = Dictionary<String, String>()
var emptyDict: Dictionary = [String: String]()
var emptyDict: Dictionary = Dictionary<String, String>()
var emptyDict: Dictionary<String, String> = [:]
var emptyDict: Dictionary<String, String> = [String: String]()
var emptyDict: Dictionary<String, String> = Dictionary<String, String>()

After you have an empty Dictionary you can add a key-value pair like this:

emptyDict["some key"] = "some value"

If you want to empty your dictionary again, you can do the following:

emptyDict = [:]

The types are still <String, String> because that is how it was initialized.


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python