twilight2 twilight2 - 19 days ago 6
Swift Question

what are the different ways of dictionary declaration in swift

what is the difference between
1.

var dict : [Int:String] = [:]
,
2.
var dict2 : [Int:String]
and

3.
var dict3 = Dictionary<Int,String>()
.

Anyone help me to understand what is the difference?

Answer

1.

var dict : [Int:String] = [:] 

This creates an empty dictionary of type [Int:String]

2.

var dict2 : [Int:String] 

This creates a dictionary of type [Int:String] but does not assign any value to it. Before using some value must be assigned to it.

3.

var dict3 = Dictionary<Int,String>() 

This is just another way to create an empty dictionary same as in method-1. Method-1 is a shorthand form of Method-3