2
$\begingroup$

From A Swift Tour — The Swift Programming Language (Swift 5):

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?

$\endgroup$
  • 1
    $\begingroup$ 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.) $\endgroup$ – Martin Berger May 24 at 10:10
  • $\begingroup$ 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. $\endgroup$ – xuq01 May 24 at 21:48
2
$\begingroup$

You did not provide an explicit type identifier in the left part of the variable declaration & initialization statement. However, by implicitly specifying an initialization value in the right part to have type int, which the compiler can infer from values of 42/50, these statements triggered the procedure of the compiler to handle S-Attributed Grammar.

$\endgroup$
  • $\begingroup$ Just to add to the Answer from Zeyi: The compiler does type inference to assign a type to the variable. This is done to do static type checking. Here would be a link to Type inference: en.wikipedia.org/wiki/Type_inference $\endgroup$ – ErebosM May 24 at 5:06
2
$\begingroup$

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

That type is then used as the declared variable's type.

It is the same logic for type checking when you do declare the type explicitly or assign to a variable, only with the difference that when the type is already fixed and it doesn't match it emits an compiler error.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.