Swift Variables
A variable is a convenient placeholder used to refer to a computer memory address.
In Swift, each variable is assigned a specific type, which determines the amount of memory the variable occupies, and different data types also determine the range of values that can be stored.
In the previous chapter, we have introducedbasic data types, including integer Int, floating-point Double and Float, Boolean Bool, and string String. In addition, Swift provides other more powerful data types, such as Optional, Array, Dictionary, Struct, and Class.
Next, we will show you how to declare and use variables in a Swift program.
Variable Declaration
Variable declaration means telling the compiler where in memory to create storage space for the variable and how large it should be.
Before using a variable, you need to use thevarkeyword to declare it, as shown below:
var variableName = <initial value>
The following is a simple example of variable declaration in a Swift program:
import Cocoa var varA = 42 print(varA) var varB:Float varB = 3.14159 print(varB)
The output of the above program is:
42 3.14159
Variable Naming
Variable names can consist of letters, digits, and underscores.
Variable names must begin with a letter or an underscore.
Swift is a case-sensitive language, so uppercase and lowercase letters are different.
Variable names can also use simple Unicode characters, as in the following example:
import Cocoa var _var = "Hello, Swift!" print(_var) var 你好 = "你好世界" var Example = "www.example.com" print(你好) print(Example)
The output of the above program is:
Hello, Swift! 你好世界 www.example.com
Variable Output
Variables and constants can be output using theprintfunction (Swift 2 replaced println with print) to output.
In strings, parentheses and backslashes can be used to insert variables, as in the following example:
import Cocoa
var name = "Example"
var site = "http://www.example.com"
print("\(name)的官网地址为:\(site)")
The output of the above program is:
Example的官网地址为:http://www.example.comOther Extensions