Swift Variables
Variables are used to store values that change; Swift declares variables with var.
Unlike C and Java, Swift variables must be initialized before they can be read; the compiler does not allow using a variable that has not been assigned a value.
This article covers declaring and modifying var, type annotation and type inference, lazy initialization, naming rules, and string interpolation; for values that will not change once set, use let — seeSwift Constants》。
Declaring Variables with var
var declares a variable that can be reassigned; the first assignment is called initialization, and each later assignment overwrites the old value.
The variable name is written after var, and the initial value appears to the right of the equals sign.
Example
import Foundation
// var declares a variable that can be reassigned after declaration
var site
=
"www.runoob.com"
(
site
)
site
=
"RUNOOB"
(
site
)
// A variable's new value can be computed from its old value
var visits
=
100
visits
=
visits
50
(
"Visits: (visits)"
)
Running result:
www.runoob.com
RUNOOB
访问量:150
The same variable can be assigned repeatedly, but each assigned value must match its current type, otherwise compilation fails.
If a line contains only a variable name and nothing else, the compiler issues a "variable is unused" warning, reminding you that you most likely forgot to write the assignment target.
Type Annotation and Type Inference
When declaring a variable you may write its type directly or let the compiler infer it; both forms are valid.
In most cases the compiler can infer the exact type from the initial value, so the type annotation can be omitted.
Example
// Type inference: inferred as Int from the initial value
var count
=
43
// Type annotation: explicitly state the type
var site
:
String
=
"RUNOOB"
var price
:
Double
=
9.9
(
count, site, price
)
Running result:
43 RUNOOB 9.9
The syntax of a type annotation is "variable name, colon, space, type", for example var site: String; the colon cannot be written as an equals sign.
When must the type be stated explicitly? In the following cases it cannot be inferred, or the inferred result is not what you expect.
| Scenario | Syntax | Reason |
|---|---|---|
| Declaration with no initial value | var name: String | No value to infer from |
| Single precision needed for a float | var ratio: Float = 0.5 | Defaults to Double |
| An integer needs a specified bit width | var small: Int8 = 10 | Inferred as Int by default |
| An empty array needs an element type | var list: [String] = [] | An empty literal cannot be inferred |
Swift's numeric literals also follow a set of default inference rules: literals with a decimal point default to Double, and integer literals default to Int.
Example
// An empty array's element type cannot be inferred and must be annotated
var names
:
[
String
]
=
[
]
names.
append
(
"Runoob"
)
(
names
)
// To get a single-precision float you must annotate it; without annotation it is inferred as Double
var ratio
:
Float
=
0.5
(
ratio
)
Running result:
["Runoob"]
0.5
You can also declare several variables on one line; each is inferred or annotated independently and their types may differ.
Example
// Declare multiple variables of the same type on one line
var x
=
1
, y
=
2
, z
=
3
(
x
y
z
)
// You can also declare variables of different types on one line, each inferred separately
var count
=
3
, ratio
=
0.5
, name
=
"RUNOOB"
(
count, ratio, name
)
Running result:
6
3 0.5 RUNOOB
The only requirement is that each variable's type be determinable: either it has an initial value or a type annotation. Writing var x = 1, y produces "type annotation missing in pattern".
Lazy Initialization of Variables
A variable does not have to be assigned on the line where it is declared; you can declare only its type and assign it later.
This is called lazy initialization; you only need to complete the assignment before reading, and the compiler tracks whether each variable has been initialized.
Example
// Declare the type first, assign it later
var site
:
String
site
=
"www.runoob.com"
(
site
)
// A variable can be assigned repeatedly; the last value takes effect
var status
=
0
status
=
1
status
=
2
(
"status ="
, status
)
Running result:
www.runoob.com
status = 2
The most common scenario for lazy initialization is when a value can be computed only after a condition holds, or only once the required data is available.
Note:Deferred initialization is not lazy. Here a single assignment is completed before use, whereas lazy is computed on first access and is a kind of property modifier, covered in 《Swift Properties》.
Variable naming rules
Swift's identifier rules are permissive, but permissive does not mean you can write anything.
A variable name may consist of letters, digits, underscores, and most Unicode characters, but it cannot start with a digit and cannot contain spaces, hyphens, or mathematical symbols.
Example
// Chinese identifier
var courseName
=
"Swift Tutorial"
// Greek letter identifier
var π
=
3.14159
(
courseName, π
)
// Recommended lowerCamelCase style
var siteName
=
"RUNOOB"
var isLoading
=
true
(
siteName, isLoading
)
Running result:
Swift 教程 3.14159
RUNOOB true
Although Chinese characters and Greek letters compile, formal projects should consistently use English lowerCamelCase to ease team collaboration and global search.
The following naming habits are worth following.
| Rule | Recommend | Not recommended |
|---|---|---|
| Use meaningful names; avoid meaningless abbreviations | maxRetryCount | mrc、a1 |
| Start Boolean values with is, has, or can | isLoading | loading |
| Do not start with an underscore | siteName | _siteName |
| Do not use keywords | className | class |
If you really must use a keyword as a name, wrap it in backticks, for example var class = "Swift", but this is not a good practice.
String Interpolation
String interpolation is the syntax that embeds the value of a variable or expression directly into a string; it is clearer than manual concatenation.
The syntax is to write a backslash followed by parentheses inside double quotes, with a variable or any expression inside the parentheses.
Example
var name
=
"Runoob"
var site
=
"www.runoob.com"
var year
=
2024
(
"Welcome to (site), the (name) tutorial was updated in (year)"
)
// Expressions can be placed inside interpolation
var a
=
3
, b
=
4
(
"(a) + (b) = (a + b)"
)
Running result:
欢迎访问 www.runoob.com,Runoob 教程更新于 2024 年
3 + 4 = 7
An expression inside interpolation cannot contain unescaped double quotes or backslashes; to write a string inside interpolation you need nested escaping or concatenation instead.
Interpolation calls a value's description property by default, so custom types can be interpolated too, outputting their description.
Note:The interpolation marker is a backslash followed by a left parenthesis \(, ending with a right parenthesis; do not omit it or write it as {}. If you really need to output a backslash, write two backslashes \\。
Common questions
The following are the questions most often asked about variables.
When should var be used?
Use var only when a value genuinely needs to change, such as counters, accumulators, and status flags; in all other cases prefer let — the full criteria are inSwift Constants》。
What if type inference is wrong?
Simply add a type annotation, for example var ratio: Float = 0.5; without the annotation, 0.5 would be inferred as Double.
Can multiple variables be declared on one line?
Yes; each variable on the line is inferred or annotated independently and their types may differ, for example var x = 1, y = 2.5; as long as each variable has an initial value or type annotation, no error occurs.