4

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

JAL
  • 41,701
  • 23
  • 172
  • 300
Wullschi
  • 43
  • 5

3 Answers3

5

Your second line works because the subscript override for Dictionary uses an Optional:

subscript(key: Key) -> Value? { get set }

Whereas the initializer for a Dictionary of type [String : AnyObject] requires concrete types:

Dictionary init

JAL
  • 41,701
  • 23
  • 172
  • 300
2

In the first example you're using a dictionary literal. The values in a dictionary literal must match the dictionary's Value type.

In the second example, you're using Dictionary's subscript(key: Key) -> Value? subscript to assign a value. Here, Value? can be optional, which you can use to remove a key/value pair by assigning nil.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
0

In the above example, myDict is inferred with non-optional AnyObject while the assigned is optional AnyObject. That is the reason for the error. This will resolve your issue.

var myDict : [String : AnyObject?] = [ "Key1" : "Value1" as AnyObject?]
JAL
  • 41,701
  • 23
  • 172
  • 300
Aman Gupta
  • 985
  • 1
  • 8
  • 18
  • Yes, but this answer does not explain *why* the subscript can take an optional, but the dictionary literal cannot. – JAL Dec 26 '16 at 17:08