patternMinor
How does a compiler infer a value's type?
Viewed 0 times
howvaluetypecompilerdoesinfer
Problem
From A Swift Tour — The Swift Programming Language (Swift 5):
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?
var myVariable = 42
myVariable = 50
let myConstant = 42A 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?
Solution
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.
Context
StackExchange Computer Science Q#109790, answer score: 2
Revisions (0)
No revisions yet.