When writing code, less is more. Programmers often try to keep their code as concise as possible to make their programs readable and efficient.
Using type inference, the compiler can automatically determine the data type of a Swift expression. We can use type inference to declare dictionaries with less code.
When we first learned how to declare a dictionary, our code looked like this:
var fruitStand: [String: Int] = [ "Apples": 12, "Bananas": 20 ]
With type inference, we can initialize fruitStand
with this syntax:
var fruitStand = [ "Apples": 12, "Bananas": 20 ]
We eliminated the type annotation [String: Int]
from the initialization.
With type inference, the compiler deduces that the keys are type String
and the values are type Int
.
To learn more about type inference, check out Swift’s Language Guide.
Instructions
Declare a dictionary called movieYears
using type inference syntax.
Include the following key-value pairs in movieYears
:
"Finding Nemo"
:2003
"Toy Story"
:1995
Print the value of movieYears
to the terminal.