We can also create element-initialized dictionaries. A single key-value pair in a dictionary refers to an element. A dictionary literal in Swift is a collection of comma-separated key-value pairs. So, dictionary literal syntax will use to create a populated dictionary.
The following is the syntax for populating a dictionary:
var nameofDictionary: [KeyType: ValueType] = [ Key1: Value1, Key2: Value2, Key3: Value3 ]
:separates the key from the value.
, all of the elements are contained.
,) separates each key-value pair.
Let’s make a
Shop dictionary to store information about Shop inventory:
var Shop: [String: Int] = [ "Juices": 21, "Snacks": 14 ];
Stringtype, and the values are of the
"Juices"with a value of
14and a key of
We can get the following result if we use
print() to output the value of
["Snacks": 14, "Juices": 21]
When we use
print() to output a dictionary, the order of the elements may not appear in the same order as when they were added.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.