1

In swift there are quite a few ways on defining a dictionary. So, are all of these identical?

var dic1 = Dictionary<String, Int>()

var dic2 = [String:Int]()

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

var dic4: Dictionary = [String:Int]()

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

var dic6: Dictionary<String, Int> = [String: Int]()
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Milad
  • 1,239
  • 3
  • 19
  • 37
  • 2
    Possible duplicate of [Swift: declare an empty dictionary](http://stackoverflow.com/questions/24033393/swift-declare-an-empty-dictionary) (see http://stackoverflow.com/a/31462410/2227743) – Eric Aya Jan 04 '16 at 15:21

2 Answers2

3

Yes, all these 6 lines do produce the same result:

  • an empty
  • mutable
  • dictionary
  • where the key has type String
  • and the value has type Int
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
2

There are still more for example:

var dic7 : [String:Int] = [:]

but yes, they are all identical.

Basically, unless the type is not included in the part right from the equation sign, type annotations in declaration lines are not needed because the compiler can infer the type.

vadian
  • 274,689
  • 30
  • 353
  • 361