Variables
Named constants are fine for values that never change during the execution of our programs but we also need to have symbols that represent values that do change as our program runs. Variables are symbols that we set up for such purposes. A variable can not only be initialized to a value when it is created, but can be changed as often as we need. Think of a variable as a box or container that has a name drawn on its side. The name of the variable always stays the same, but what is inside the box can be changed.
Types
In order to declare named constants or variables, we need to specifically declare what type of value they should hold. This idea is known as strong typing. By declaring the types of our symbols, it helps the compiler to detect problems that might arise from mixing different data types. If, as is the case with constants, we provide an initializer value, the compiler will determine the type of the constant from the initializer so we needn't declare it ourselves. The table below lists the fundamental (or intrinsic) types supported by Swift.
Type | Keyword |
---|---|
Boolean | Bool |
Character | Character |
8-Bit Integer | Int8 |
16-Bit Integer | Int16 |
32-Bit Integer | Int32 |
64-Bit Integer | Int64 |
32-Bit Floating Point | Float |
64-Bit Floating Point | Double |
String | String |
Void | Void |
Declaration Syntax
Named constants must be initialized to a specific value when they are declared. Once initialized, they can not have their value changed during the execution of the program.
The syntax for a constant declaration consists of the keyword var
, the name of the variable (see rules for identifiers), optional colon (:) with type, optional equal sign (=
) followed by the initializer value for the variable. The declaration ends at the newline. If no initializer is provided, the variable will have the default value for that type. If an initializer is supplied, then the type is not required but will be inferred from the initializer.
Examples of statements used to declare variables are illustrated below.
Assignment
The thing that separates variables from constants is that we can change their value at any point in the program. This is done with an assignment statement. Assignment statements consiste of the variable name, the equals sign, and a new value for the variable. Examples of statements used to assign new values to a variable are illustrated below.
Questions
- Who?
- What?
- Where?
Projects
More ★'s indicate higher difficulty level.
References
- [[Swift Community]]
- [[Swift Language Guide]]
- [[Swift Language Reference]]
- [[Swift Programming Language]], Apple Inc.
- [[Swift Doc]]
- [[We Heart Swift]]
- [[Swift Cookbook]]
- [[Swift Playground]]
- [[Swift at TutorialsPoint]]
- [[Hacking with Swift]]