# How does a compiler infer a value's type?

var myVariable = 42
myVariable = 50
let myConstant = 42


A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that myVariable is an integer because its initial value is an integer.

How does this work?

• Roughly: the compiler looks carefully at the program. For example in the program M+N the very presence of + forces both M and N to be of type Integer. Now apply this recursively to the whole program. Details are much more complicated, and explained in great detail in the wonderful textbook Types and Programming Languages, one of the best textbooks in all of computer science. (This is probably not the answer you want.) – Martin Berger May 24 at 10:10
• I don't think Swift actually does full type inference/type reconstruction (Algorithm W), rather it does bidirectional type checking. There are some subtle differences between them. – xuq01 May 24 at 21:48

When the compiler sees the var <identifier> = <expression>; construct it can parse the <expression> out of which a type will emerge.