Swift constant
Once a constant is set, its value cannot be changed while the program is running.
Constants can be any data type such as integer constants, floating-point constants, character constants, or string constants. There are also constants of enumerumered types:
Constants are similar to variables in that they cannot be changed once they are set, and the values of variables can be changed at will.
Constant declaration
Constants are declared using the keyword let, and the syntax is as follows:
let constantName = <initial value>
Here's an example of a constant used in a simple Swift program:
import Cocoa let constA = 42 print(constA)
The above procedures are performed as follows:
42
Type label
When you declare a constant or variable, you can add a type annotation to indicate the type of constant or value to store in the variable. I f you want to add a type label, you need to add a colon and space after the constant or variable name, and then add the type name.
var constantName:<data type> = <optional initial value>
Here's a simple example of a constant usage type label in Swift. It is important to note that the initial value must be defined as a constant:
import Cocoa let constA = 42 print(constA) let constB:Float = 3.14159 print(constB)
The above procedures are performed as follows:
42 3.14159
Constant naming
Constants can be named by letters, numbers, and underscores.
Constants need to start with letters or underscores.
Swift is a case-sensitive language, so capital letters are not the same as lowercase.
Constant names can also use simple Unicode characters, as follows:
import Cocoa let _const = "Hello, Swift!" print(_const) let 你好 = "你好世界" print(你好)
The above procedures are performed as follows:
Hello, Swift! 你好世界
Constant output
Variables and constants can be output using the print (swift 2 replaces println) function.
In a string, you can insert a constant with parentheses and backslashes, as follows:
import Cocoa let name = "W3Cschool教程" let site = "http://www.w3cschool.cn" print("\(name)的官网地址为:\(site)")
The above procedures are performed as follows:
W3Cschool教程的官网地址为:http://www.w3cschool.cn