Swift: Creating a Dictionary Literal

Creating a Dictionary Literal in Swift:

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
]

  • Both the key and the value have a type annotation.
  • Each key is unique.
  • The keys and values must be of the same type as their corresponding values.
  • A colon : separates the key from the value.
  • Within brackets [], all of the elements are contained.
  • A comma (,) 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
];

  • The keys are of the String type, and the values are of the Int type.
  • In our dictionary, we have two key-value pairs.
  • The key for one pair is "Juices" with a value of 21.
  • The other pair has a value of 14 and a key of "Snacks".

We can get the following result if we use print() to output the value of Shop:

["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.

Helpful Tools:

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.

Scroll to Top
%d bloggers like this: