Review the code. var capitalCities = [ " USA " : " Washington D.C. " , " Spain " : " Madrid " , " Peru " : " Lima " ] Which two statements add the capital city of " Italy " to the dictionary? (Choose 2.)
Correct Answer: C, E
Explanation:
Comprehensive and Detailed Explanation From App Development with Swift domains: This question falls under Swift Programming Language , specifically the domain for managing data using collection types , with emphasis on dictionaries . In Swift, a dictionary stores data as key value pairs , so in this example the country name is the key and the capital city is the value. To add a new entry, Swift supports two standard approaches. The first is subscript assignment , which is shown in option C : capitalCities[ " Italy " ] = " Rome " . Apple’s documentation explains that you can add a key-value pair to a dictionary by assigning a value for a new key through the dictionary subscript. The second correct approach is option E : capitalCities.updateValue( " Rome " , forKey: " Italy " ). Apple documents that updateValue(_:forKey:) updates the value for an existing key, or adds a new key-value pair if the key does not already exist . That makes it equally valid for inserting " Italy " : " Rome " into the dictionary. The incorrect options fail for different reasons. A reverses the key and value, making " Rome " the key and " Italy " the value. B is wrong because append is used with arrays, not dictionaries. D is not the standard valid insertion syntax for Swift dictionaries in this context; Swift’s documented mutation approaches here are subscript assignment and updateValue. Therefore, the two correct answers are C and E .
Demo Practice Mode
You are viewing only the questions marked as Demo.