As far as I know, there are 4 ways to declare a dictionary in Swift:
var dict1: Dictionary<String, Double> = [:]
var dict2 = Dictionary<String, Double>()
var dict3: [String:Double] = [:]
var dict4 = [String:Double]()
It seems these four options yields the same result.
What's the difference between these?
Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.
Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.
The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ).
Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you can't insert a value of the wrong type into a collection by mistake.
All you're doing is noticing that you can:
Use explicit variable typing, or let Swift infer the type of the variable based on the value assigned to it.
Use the formal specified generic struct notation Dictionary<String,Double>
, or use the built-in "syntactic sugar" for describing a dictionary type [String:Double]
.
Two times two is four.
And then there are in fact some possibilities you've omitted; for example, you could say
var dict5 : [String:Double] = [String:Double]()
And of course in real life you are liable to do none of these things, but just assign an actual dictionary to your variable:
var dict6 = ["howdy":1.0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With