Swift Introduction | Values, Variables, and Operations | Variables, Constants, and Types

Declare a variable before using it. Using an undeclared variable or redeclaring an existing variable causes an error.

var variable = value
var variable:Type = value

Variables are usually declared with an initial value. To declare a variable without assigning a value immediately, specify its type.

var variable:Type

Constants

Use a constant when a value must not change later.

let constant = value
let constant:Type = value

Declare a constant and assign its value together. The assigned value cannot be changed afterward.

Variable Types

When declaring a variable or constant, you can specify its type as well as its name. Every Swift variable has a type. If you omit the type in a declaration such as var variable = value, Swift infers it from the assigned value. A declaration containing only var variable is invalid.

Swift is a statically typed language. Each variable has a type and can store only values of that type.

Main Types

Integers

Type Description
Int A general integer. Its width is 32 or 64 bits depending on the CPU.
UInt Similar to Int, but unsigned. It cannot represent negative values.
Byte An 8-bit value.
Int8, Int16, Int32, Int64 Integer types with an explicit width. Unsigned types such as UInt8 are also available.

Floating-Point Numbers

Type Description
Float A 32-bit floating-point value.
Double A 64-bit floating-point value.
Float32, Float64, Float80, Float96 Floating-point types used when specifying a width explicitly.

Text

Type Description
String General text.
Character A single character.

Boolean Values

Type Description
Bool A logical value: true or false.

These can be considered basic types. Swift also supports more complex values such as arrays, objects, tuples, and optionals, which are explained separately.