Basics: Type Safety and Type Inference

If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type.

Enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.

Is particularly useful when you declare a constant or variable with an initial value.

Let meaningOfLife = 42
// meaningOfLife is inferred to be of type Int
Let pi = 3.14159
// pi is inferred to be of type Double
Let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double

Additional information

  • Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. .
  • Type-checking helps you avoid errors when you’re working with different types of values. .
  • Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.

Related concepts

Type Safety and Type Inference

Basics: Type Safety and Type Inference — Structure map

Clickable & Draggable!

Basics: Type Safety and Type Inference — Related pages: