When I add a value of type 'AnyObject?' to a dictionary of Type '[String : AnyObject]' in the following way, the value can not by added, which is actually what I've expected. Assigning an optional type to a non-optional type should fail in my opinion.
var myDict : [String : AnyObject] = [ "Key1" : "Value1" as AnyObject? ]
But why does this procedure work if I first initialize an empty dictionary and then add the value to it?
var myDict = [String : AnyObject]()
myDict["Key1"] = "Value1" as AnyObject?
I've seen this approach in the GenericKeychain example from Apple https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html
Your second line works because the
subscript
override for Dictionary uses an Optional:Whereas the initializer for a Dictionary of type
[String : AnyObject]
requires concrete types: