Reputation: 4471
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?
Upvotes: 29
Views: 42523
Reputation: 534950
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]
Upvotes: 55