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 constant, floating point constant, character constant, or string constant. There are also constants for enumerated types:
Constants are similar to variables, except 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 use keyword let
to declare the syntax is as follows:
let constantName = <initial value>
The following is an example of using constants in a simple Swift program:
import Cocoa
let constA = 42
print(constA)
The execution results of the above procedures are as follows:
42
Type annotation
When you declare a constant or variable, you can add a type annotation to indicate 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 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 of the use of type annotations for constants in Swift. It is important to note that when a constant is defined,it must have an initial value:
import Cocoa
let constA = 42
print(constA)
let constB:Float = 3.14159
print(constB)
The execution results of the above procedures are as follows:
42
3.14159
Constant naming
The naming of constants can consist of letters, numbers, and underscores.
Constants need to start with a letter or an underscore.
Swift is a case-sensitive language, so uppercase and lowercase letters are different.
Constant names can also be used with a simple Unicode
characters, as anexample:
import Cocoa
let _const = "Hello, Swift!"
print(_const)
let Hello="Hello World"
print(Hello)
The execution results of the above procedures are as follows:
Hello, Swift!
Hello World
Constant output
Variables and constants can be used print
(swift 2 replaces print with println) function to output.
You can insert constants in a string using parentheses and backslashes, as shown in the following example:
import Cocoa
let name = "Novice Tutorial"
let site = "http://www.runoob.com"
print("\(name) The official website address of is :\(site)")
The execution results of the above procedures are as follows:
The official website address of Cainiao Tutorial is:http://www.runoob.com