Swift Constants
Once a constant is set, its value cannot be changed during program execution.
Constants can be of any data type, such as integer constants, floating-point constants, character constants, or string constants. There are also constants of enumeration types:
Constants are similar to variables, the difference being that once a constant's value is set, it cannot be changed, while a variable's value can be changed at will.
Constant Declaration
Constants are declared using the keywordletwith the following syntax:
let constantName = <initial value>
The following is a simple example of using constants in a Swift program:
import Cocoa let constA = 42 print(constA)
The above program execution result is:
42
Type Annotation
When you declare a constant or variable, you can add a type annotation to specify the type of value to be stored in the constant or variable. To add a type annotation, place a colon and a space after the constant or variable name, followed by 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. Note that constants must have an initial value when defined:
import Cocoa let constA = 42 print(constA) let constB:Float = 3.14159 print(constB)
The above program execution result is:
42 3.14159
Constant Naming
Constant names can consist of letters, numbers, and underscores.
Constants must start with a letter or an underscore.
Swift is a case-sensitive language, so uppercase and lowercase letters are different.
Constant names can also use simple Unicode characters, as in the following example:
import Cocoa let _const = "Hello, Swift!" print(_const) let 你好 = "你好世界" print(你好)
The above program execution result is:
Hello, Swift! 你好世界
Constant Output
Variables and constants can be output using the print function (in Swift 2, print replaced println).
In strings, parentheses and backslashes can be used to insert constants, as in the following example:
import Cocoa
let name = "Example"
let site = "http://www.example.com"
print("\(name)的官网地址为:\(site)")
The above program execution result is:
Example的官网地址为:http://www.example.comOther Extensions