Swift Variables
A variable is a convenient placeholder used to reference a computer memory address.
In Swift, each variable is specified with a particular type, which determines the size of memory it occupies. Different data types also determine the range of values that can be stored.
In the previous chapter, we introduced basic data types, including integers (Int), floating-point numbers (Double and Float), boolean types (Bool), and string types (String). Additionally, Swift offers other 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
Before using a variable, you need to declare it using the var keyword, as shown below:
var variableName = <initial value>
Here 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, numbers, and underscores.
Variable names must start with a letter or an underscore.
Swift is a case-sensitive language, so uppercase and lowercase letters are distinct.
Variable names can also use simple Unicode characters, as shown in the following example:
import Cocoa
var _var = "Hello, Swift!"
print(_var)
var 你好 = "你好世界"
var tutorialpro.org = "www.tutorialpro.org"
print(你好)
print(tutorialpro.org)
The output of the above program is:
Hello, Swift!
你好世界
www.tutorialpro.org
Variable Output
Variables and constants can be output using the print function (Swift 2 replaced println with print).
Variables can be inserted into strings using parentheses and a backslash, as shown in the following example:
import Cocoa
var name = "tutorialpro.org"
var site = "http://www.tutorialpro.org"
print("\(name)'s website address is: \(site)")
The output of the above program is:
tutorialpro.org's website address is: http://www.tutorialpro.org