Swift constants


Once a constant is set, its value cannot be changed while the program is running.

Constant can be any data type such as: integer constant, floating point constant, character constant or string constant. There are also constants of enumeration types:

Constants are similar to variables. The difference is that the value of a constant cannot be changed once it is set, while the value of a variable can be changed at will.


Constant declaration

Constant is declared using the keyword let, the syntax is as follows:

let constantName = <initial value>

The following is used in a simple Swift program Example of constant:

import Cocoa

let constA = 42
print(constA)

The execution result of the above program is:

42

Type annotation

When you declare a constant or variable, you can add a type annotation (type annotation), indicating the type of value to be stored in the constant or variable. If you want to add a type annotation, you need to add a colon and a space after the constant or variable name, and then add the type name.

var constantName:<data type> = <optional initial value>

The following is a simple example demonstrating the use of type annotations for constants in Swift. It should be noted that the initial value must be used when defining constants:

import Cocoa

let constA = 42
print(constA)

let constB:Float = 3.14159

print(constB)

The execution result of the above program is:

42
3.14159

Constant naming

The name of the constant can be composed of letters and numbers and underline.

Constants need to start with a letter or underscore.

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

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

import Cocoa

let _const = "Hello, Swift!"
print(_const)

let 你好 = "你好世界"
print(你好)

The execution result of the above program is:

Hello, Swift!
你好世界

Constant 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 constants in a string, as shown in the following example:

import Cocoa

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

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

The execution result of the above program is:

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