Swift variables


A variable is a convenient placeholder used to reference a computer memory address.

Swift Each variable is assigned a specific type, which determines the size of the memory occupied by the variable. Different data types also determine the range of values ​​that can be stored.

In the previous chapter, we have introduced basic data types to you, including integer Int, floating-point numbers Double and Float, Boolean type Bool, and string type String. In addition, Swift also provides other more powerful data types, such as Optional, Array, Dictionary, Struct, and Class.

Next we will introduce how to declare and use variables in Swift programs.


Variable declaration

Variable declaration means telling the compiler where in memory to create how much storage space for the variable.


Before using a variable, you need to declare it using the var keyword, as shown below:

var variableName = <initial value>

The following is a variable in a Swift program Simple example of declaration:

import Cocoa

var varA = 42
print(varA)

var varB:Float

varB = 3.14159
print(varB)

The execution result of the above program is:

42
3.14159

Variable naming

The variable name can be composed of letters, numbers and underscores.

Variable names need to start with a letter or underscore.

Swift is a case-sensitive language, so uppercase and lowercase letters are different.

Variable names can also use simple Unicode characters, as shown in the following example:

import Cocoa

var _var = "Hello, Swift!"
print(_var)

var 你好 = "你好世界"
var php中文网 = "www.php.cn"
print(你好)
print(php中文网)

The execution result of the above program is:

Hello, Swift!
你好世界
www.php.cn

Variable output

Variables and constants can be output using the print (swift 2 replaces println with print) function.

You can use brackets and backslashes to insert variables in a string, as shown in the following example:

import Cocoa

var name = "php中文网"
var site = "http://www.php.cn"

print("\(name)的官网地址为:\(site)")

The execution result of the above program is:

php中文网的官网地址为:http://www.php.cn