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

var varB:Float

varB = 3.14159

The above program execution results:


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!"

var 你好 = "你好世界"
var 本教程 = ""

The above program execution results:

Hello, Swift!

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 = ""


The above program execution results: