9.7. Swift constant

发布时间 : 2025-10-25 13:33:47 UTC      

Page Views: 9 views

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.

9.7.1. 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 

9.7.2. 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 

9.7.3. 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 

9.7.4. 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 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。