In Swift, you can declare and initialize an empty Dictionary with type String
for keys and type Any
for values in 4 different ways:
var myDic1 = [String : Any]()
var myDic2 = Dictionary<String, Any>()
var myDic3: [String : Any] = [:]
var myDic4: Dictionary<String, Any> = [:]
These will all give you the same result which is an empty Dictionary with String
s as the keys and Any
s as the values.
[String : Any]
is just shorthand for Dictionary<String, Any>
. They mean the same thing but the shorthand notation is preferred.
In cases 1 and 2 above, the types of the variables are inferred by Swift from the values being assigned to them. In cases 3 and 4 above, the types are explicitly assigned to the variables, and then they are initialized with an empty dictionary [:]
.
When you create a dictionary like this:
var myDic5 = [:]
Swift has nothing to go on, and it gives the error:
Empty collection literal requires an explicit type
Historical Note: In older versions of Swift, it inferred [:]
to be of type NSDictionary
. The problem was that NSDictionary
is an immutable type (you can't change it). The mutable equivalent is an NSMutableDictionary
, so these would work:
var myDic6: NSMutableDictionary = [:]
or
var myDic7 = NSMutableDictionary()
but you should prefer using cases 1 or 3 above since NSMutableDictionary
isn't a Swift type but instead comes from the Foundation framework. In fact, the only reason you were ever able to do var myDic = [:]
is because you had imported the Foundation framework (with import UIKit
, import Cocoa
, or import Foundation
). Without importing Foundation, this was an error.