Optional AnyObject Values ​​in the Swift Dictionary

When do I add a value like "AnyObject?" into a dictionary of type '[String: AnyObject]' as follows, the value cannot be added, which is actually what I expected. Assigning an optional type to an optional type will not work 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 a value to it?

var myDict = [String : AnyObject]()
myDict["Key1"] = "Value1" as AnyObject?

I saw this approach in Apple's GenericKeychain example https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html

+4
source share
3 answers

, subscript :

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

[String : AnyObject] :

Init dictionary

+5

. Value.

Dictionary subscript(key: Key) -> Value?. Value? , /, nil.

+2

myDict AnyObject, AnyObject. . .

var myDict : [String : AnyObject?] = [ "Key1" : "Value1" as AnyObject?]
0

Source: https://habr.com/ru/post/1664931/


All Articles