Type Inference
If a variable or constant declaration is not annotated explicitly with a type, the declaration's type is inferred from the initial value.
Basic Literals
Decimal integer literals and hex literals are inferred to type Int
.
Unsigned fixed-point literals are inferred to type UFix64
.
Signed fixed-point literals are inferred to type Fix64
.
Similarly, for other basic literals, the types are inferred in the following manner:
Literal Kind | Example | Inferred Type (x) |
---|---|---|
String literal | let x = "hello" | String |
Boolean literal | let x = true | Bool |
Nil literal | let x = nil | Never? |
Array Literals
Array literals are inferred based on the elements of the literal, and to be variable-size. The inferred element type is the least common super-type of all elements.
Dictionary Literals
Dictionary literals are inferred based on the keys and values of the literal. The inferred type of keys and values is the least common super-type of all keys and values, respectively.
Ternary Expression
Ternary expression type is inferred to be the least common super-type of the second and third operands.
Functions
Functions are inferred based on the parameter types and the return type.
Type inference is performed for each expression / statement, and not across statements.
Ambiguities
There are cases where types cannot be inferred. In these cases explicit type annotations are required.