Swift Constants
Once set, the value of a constant 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, but the difference is that the value of a constant cannot be changed once set, whereas the value of a variable can be changed at will.
Constant Declaration
Constants are declared using the keyword let, with the following syntax:
let constantName = <initial value>
Below is an example of using a constant in a simple Swift program:
import Cocoa
let constA = 42
print(constA)
The output of the above program is:
42
Type Annotation
You can add a type annotation when declaring a constant or variable to specify the type of value the constant or variable can store. To add a type annotation, follow the constant or variable name with a colon and a space, then the type name.
var constantName:<data type> = <optional initial value>
Below is a simple example demonstrating the use of type annotation in Swift constants. Note that a constant must be initialized when defined:
import Cocoa
let constA = 42
print(constA)
let constB:Float = 3.14159
print(constB)
The output of the above program 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 considered 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 output of the above program is:
Hello, Swift!
你好世界
Constant Output
Variables and constants can be output using the print function (print replaced println in Swift 2).
Constants can be inserted into a string using parentheses and a backslash, as shown in the following example:
import Cocoa
let name = "tutorialpro.org"
let site = "http://www.tutorialpro.org"
print("\(name)'s website address is: \(site)")
The output of the above program is:
tutorialpro.org's website address is: http://www.tutorialpro.org