Skip to main content

Variables

Use var to declare a variable. Every variable must be initialized at the point of declaration.

Declaration

var count = 0
var name = "Alice"
var active = true

Type Annotations

The compiler infers the type from the initial value. To declare the type explicitly, write a colon (:) and the type name after the variable name.

var implicit_int = 42           // inferred as Int
var explicit_float: Float = 42 // declared as Float

Type annotations are required when the initial value doesn't carry enough type information:

var optional_int: Int? = nil
var empty_array: [Int] = []
var empty_map: [String: Int] = [:]

Reassignment

Variables can be reassigned to a new value of the same type.

var x = 10
x = 20

Variables are not reactive. Reassigning a variable does not trigger any updates elsewhere. Reactivity is a property of class properties and component state — see Classes and Components for details.

Type Conversions

Types are strictly enforced. The only implicit conversion is from Int to Float.

var i = 42
var f: Float = i // ok — implicit Int to Float
f = i // ok

i = f // error — Float does not implicitly convert to Int
var s: String = i // error — no implicit conversion to String

To convert a value to String, use string interpolation:

var i = 42
var s = "\{i}"