Swift constant
Constant Once set, the program is running you can not change its value.
Constants can be of any type of data, such as: integer constant, floating-point constants, character constants or string constants. There are also enumerated type constants:
Constants are like variables except that the value of a constant can not be changed once set, and the value of a variable can be altered.
Constant declaration
Constants are declared using the keywordlet the following syntax:
let constantName = <initial value>
The following is a simple instance of Swift program constants:
import Cocoa let constA = 42 print(constA)
The above program execution results:
42
Type annotation
When you declare a variable or constant can add type annotations (type annotation), illustrate the type of constant or variable to store the value. If you want to add a type annotation, you need to add a colon and space after constant or variable name, and then add the type name.
var constantName:<data type> = <optional initial value>
The following is a simple example to demonstrate the Swift is in constant use type annotations. Note that the initial value must be constant defines:
import Cocoa let constA = 42 print(constA) let constB:Float = 3.14159 print(constB)
The above program execution results:
42 3.14159
Named Constant
Named constants can consist of letters, numbers and underscores.
The constant need to start with a letter or an underscore.
Swift is a case-sensitive language, so uppercase and lowercase letters are not the same.
You can also use a simple constant name Unicode characters following examples:
import Cocoa let _const = "Hello, Swift!" print(_const) let 你好 = "你好世界" print(你好)
The above program execution results:
Hello, Swift! 你好世界
Constant output
Variables and constants can use print (swift 2 replaces the print println) function to output.
Parentheses can be used in the string with a backslash to insert constants as examples:
import Cocoa let name = "本教程" let site = "http://www.w3write.com" print("\(name)的官网地址为:\(site)")
The above program execution results:
本教程的官网地址为:http://www.w3write.com