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 use keyword The following is an example of using constants in a simple Swift program: The execution results of the above procedures are as follows: 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. 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: The execution results of the above procedures are as follows: 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 The execution results of the above procedures are as follows: Variables and constants can be used You can insert constants in a string using parentheses and backslashes, as shown in the following example: The execution results of the above procedures are as follows: 9.7.1. Constant declaration #
let
to declare the syntax is as follows:let constantName = <initial value>
import Cocoa
let constA = 42
print(constA)
42
9.7.2. Type annotation #
var constantName:<data type> = <optional initial value>
import Cocoa
let constA = 42
print(constA)
let constB:Float = 3.14159
print(constB)
42
3.14159
9.7.3. Constant naming #
Unicode
characters, as anexample:import Cocoa
let _const = "Hello, Swift!"
print(_const)
let Hello="Hello World"
print(Hello)
Hello, Swift!
Hello World
9.7.4. Constant output #
print
(swift 2 replaces print with println) function to output.import Cocoa
let name = "Novice Tutorial"
let site = "http://www.runoob.com"
print("\(name) The official website address of is :\(site)")
The official website address of Cainiao Tutorial is:http://www.runoob.com