Latest web development tutorials

Swift variable

Variable is a convenient placeholder for reference computer memory addresses.

Swift each variable is assigned a specific type, which determines the size of the variable memory for the different data types can also determine the range of values ​​that can be stored.

The last chapter we have to introduce the basic data types , including plastic Int, Float and Double Float, Bool Boolean type and string type String. In addition, Swift also provides other, more powerful data type, Optional, Array, Dictionary, Struct, Class, and the like.

Next, we will discuss how to declare the Swift program and you use variables.


Variable declaration

Variable declarations mean to tell the compiler to create much storage space in memory which position is variable.

Before using a variable, you need to use thevar keyword to declare it as follows:

var variableName = <initial value>

The following is a simple example of a Swift program variable declaration:

import Cocoa

var varA = 42
print(varA)

var varB:Float

varB = 3.14159
print(varB)

The above program execution results:

42
3.14159

Variable naming

Variable names can consist of letters, numbers and underscores.

Variable names need to start with a letter or an underscore.

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

You can also use a simple variable name Unicode characters following examples:

import Cocoa

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

var 你好 = "你好世界"
var 本教程 = "www.w3big.com"
print(你好)
print(本教程)

The above program execution results:

Hello, Swift!
你好世界
www.w3big.com

Variable output

Variables and constants can useprint (swift 2 replaces the print println) function to output.

Parentheses can be used in the string with a backslash to insert variables following examples:

import Cocoa

var name = "本教程"
var site = "http://www.w3big.com"

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

The above program execution results:

本教程的官网地址为:http://www.w3big.com