Cody Cody - 6 months ago 9
Swift Question

Why Swift has many different ways to initialize a dictionary?

Here 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]()

What's the benefit of this design? It seems four options yields the same result. Doesn't it confuse leaner and hard to define a consistent coding style in teamwork?


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]