Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways to initialize a dictionary in Swift?

Tags:

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?

like image 746
Cody Avatar asked May 24 '16 03:05

Cody


People also ask

How do you initialize a new dictionary?

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.

What is dictionary and write syntax in Swift?

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.

Which type is defined for key in dictionary in Swift?

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 ( [:] ).

Why is dictionary unordered in Swift?

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.


1 Answers

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]
like image 147
matt Avatar answered Sep 27 '22 22:09

matt