What does “dictionary literal” mean?

A “dictionary literal” is a shorthand way of creating a dictionary with a fixed set of keys and values.

In this case, the code snippet shows an example of creating a dictionary with strings as the keys and integers as the values:

let myDict: [String: Int] = [
    "apple": 10,
    "banana": 20,
    "orange": 30
]

print(myDict)

// Output: ["apple": 10, "banana": 20, "orange": 30]
  • The code above creates a dictionary called “myDictionary” and initializes it to a dictionary literal, which is enclosed in square brackets.
  • The keys and values are separated by colons, and each key-value pair is separated by a comma.
  • This dictionary has three key-value pairs for the fruits “apple”, “banana”, and “orange”, with values 10, 20, and 30.
  • The type of the dictionary is explicitly specified using the `[String: Int]` syntax, where
    • “String” specifies the key type
    • and “Int” specifies the value type.

Get to know more about how to declare a dictionary, accessing or modifying values or creating empty dictionaries in this article.

Write less code using type inference

“Type inference” is the ability of the compiler to automatically determine the data type of a variable based on the context in which it is used.

  • In the example aboce, the variable “myDict” is a dictionary with keys of type “String” and values of type “Int”.
  • The type of the dictionary is explicitly declared using `[String: Int]` syntax.

However, Swift also allows the compiler to infer the type of a variable using type inference. For example, instead of declaring the type of the variable “myDict” explicitly, we could simply use the following code:

let myDict = [
    "apple": 10,
    "banana": 20,
    "orange": 30
]

print(myDict)

// Output: ["apple": 10, "banana": 20, "orange": 30]
  • In this case, the type of the “myDict” variable is inferred automatically by the compiler based on the types of the keys and values passed to the dictionary.
  • Since the keys are of type “String” and the values are of type “Int”, the compiler infers that the type of the dictionary is “[String: Int]”.

Quick notes

  • Type inference allows us to write more concise and readable code by reducing the amount of redundant type information we need to declare explicitly.

Leave a Reply

Your email address will not be published. Required fields are marked *