Composite Type Fields
Last updated
Last updated
Fields are declared like variables and constants. However, the initial values for fields are set in the initializer, not in the field declaration. All fields must be initialized in the initializer, exactly once.
Having to provide initial values in the initializer might seem restrictive, but this ensures that all fields are always initialized in one location, the initializer, and the initialization order is clear.
The initialization of all fields is checked statically and it is invalid to not initialize all fields in the initializer. Also, it is statically checked that a field is definitely initialized before it is used.
The initializer's main purpose is to initialize fields, though it may also contain other code. Just like a function, it may declare parameters and may contain arbitrary code. However, it has no return type, i.e., it is always Void
.
The initializer is declared using the init
keyword.
The initializer always follows any fields.
There are three kinds of fields:
Constant fields are also stored in the composite value, but after they have been initialized with a value they cannot have new values assigned to them afterwards. A constant field must be initialized exactly once.
Constant fields are declared using the let
keyword.
Variable fields are stored in the composite value and can have new values assigned to them.
Variable fields are declared using the var
keyword.
Synthetic fields are not stored in the composite value, i.e. they are derived/computed from other values. They can have new values assigned to them.
Synthetic fields are declared using the synthetic
keyword.
Synthetic fields must have a getter and a setter. Getters and setters are explained in the next section. Synthetic fields are explained in a separate section.
In initializers, the special constant self
refers to the composite value that is to be initialized.
Field types must be storable. Non-storable types are:
Functions
Accounts (AuthAccount
/ PublicAccount
)
Transactions
Fields can be read (if they are constant or variable) and set (if they are variable), using the access syntax: the composite value is followed by a dot (.
) and the name of the field.
Note that it is invalid to provide the initial value for a field in the field declaration.
The field access syntax must be used to access fields – fields are not available as variables.
The initializer is not automatically derived from the fields, it must be explicitly declared.
A composite value can be created by calling the constructor and providing the field values as arguments.
The value's fields can be accessed on the object after it is created.
Field Kind
Stored in memory
Assignable
Keyword
Variable field
Yes
Yes
var
Constant field
Yes
No
let
Synthetic field
No
Yes
synthetic