Swift variable

A variable is a convenient placeholder that refers to a computer's memory address.

Swift specifies a specific type of variable that determines how much memory the variable consumes, and different data types determine the range of values that can be stored.

In the previous section, we've covered basic data types, including Shaping Int, Floating Doble and Float, Boolean-type Bool, and string-type String. Swift also offers other, more powerful data types, optional, Array, Dictionary, Struct, and Class.

Next we'll show you how to declare and use variables in a Swift program.


Variable declaration

Variable declarations mean telling the compiler where in memory how much storage space is created for the variable.

Before you can use a variable, you need to declare it with the var keyword, as follows:

var variableName = <initial value>

Here's a simple example of variable declarations in a Swift program:

import Cocoa

var varA = 42
print(varA)

var varB:Float

varB = 3.14159
print(varB)

The above procedures are performed as follows:

42
3.14159

The variable is named

Variable names can consist of letters, numbers, and underscores.

The variable name needs to start with a letter or underscore.

Swift is a case-sensitive language, so capital letters are not the same as lowercase.

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

import Cocoa

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

var 你好 = "你好世界"
var W3Cschool教程 = "www.w3cschool.cn"
print(你好)
print(W3Cschool教程)

The above procedures are performed as follows:

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

The variable output

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

You can insert variables in a string using parentheses and backslashes, as in the following example:

import Cocoa

var name = "W3Cschool教程"
var site = "http://www.w3cschool.cn"

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

The above procedures are performed as follows:

W3Cschool教程的官网地址为:http://www.w3cschool.cn