Type Inference
🚧 Status: Only basic type inference is implemented.
If a variable or constant declaration is not annotated explicitly with a type, the declaration's type is inferred from the initial value.
Integer literals are inferred to type Int
.
let a = 1
// `a` has type `Int`
Array literals are inferred based on the elements of the literal, and to be variable-size.
let integers = [1, 2]
// `integers` has type `[Int]`
// Invalid: mixed types
//
let invalidMixed = [1, true, 2, false]
Dictionary literals are inferred based on the keys and values of the literal.
let booleans = {
1: true,
2: false
}
// `booleans` has type `{Int: Bool}`
// Invalid: mixed types
//
let invalidMixed = {
1: true,
false: 2
}
Functions are inferred based on the parameter types and the return type.
let add = (a: Int8, b: Int8): Int {
return a + b
}
// `add` has type `((Int8, Int8): Int)`
Type inference is performed for each expression / statement, and not across statements.
There are cases where types cannot be inferred. In these cases explicit type annotations are required.
// Invalid: not possible to infer type based on array literal's elements.
//
let array = []
// Instead, specify the array type and the concrete element type, e.g. `Int`.
//
let array: [Int] = []
// Invalid: not possible to infer type based on dictionary literal's keys and values.
//
let dictionary = {}
// Instead, specify the dictionary type and the concrete key
// and value types, e.g. `String` and `Int`.
//
let dictionary: {String: Int} = {}
// Invalid: not possible to infer type based on nil literal.
//
let maybeSomething = nil
// Instead, specify the optional type and the concrete element type, e.g. `Int`.
//
let maybeSomething: Int? = nil