Cody Cody - 2 years ago 75
Swift Question

Different way to initialize a dictionary in Swift?

As I known, 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 ?

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download