Skip to main content

Type Annotations

When declaring a constant or variable, an optional type annotation can be provided, to make it explicit what type the declaration has.

If no type annotation is provided, the type of the declaration is inferred from the initial value.

For function parameters a type annotation must be provided.


_20
// Declare a variable named `boolVarWithAnnotation`, which has an explicit type annotation.
_20
//
_20
// `Bool` is the type of booleans.
_20
//
_20
var boolVarWithAnnotation: Bool = false
_20
_20
// Declare a constant named `integerWithoutAnnotation`, which has no type annotation
_20
// and for which the type is inferred to be `Int`, the type of arbitrary-precision integers.
_20
//
_20
// This is based on the initial value which is an integer literal.
_20
// Integer literals are always inferred to be of type `Int`.
_20
//
_20
let integerWithoutAnnotation = 1
_20
_20
// Declare a constant named `smallIntegerWithAnnotation`, which has an explicit type annotation.
_20
// Because of the explicit type annotation, the type is not inferred.
_20
// This declaration is valid because the integer literal `1` fits into the range of the type `Int8`,
_20
// the type of 8-bit signed integers.
_20
//
_20
let smallIntegerWithAnnotation: Int8 = 1

If a type annotation is provided, the initial value must be of this type. All new values assigned to variables must match its type. This type safety is explained in more detail in a separate section.


_12
// Invalid: declare a variable with an explicit type `Bool`,
_12
// but the initial value has type `Int`.
_12
//
_12
let booleanConstant: Bool = 1
_12
_12
// Declare a variable that has the inferred type `Bool`.
_12
//
_12
var booleanVariable = false
_12
_12
// Invalid: assign a value with type `Int` to a variable which has the inferred type `Bool`.
_12
//
_12
booleanVariable = 1