一、常量与变量
1.常量与变量的表示
在Swift中实用let表示常量,使用var表示变量。Use let to make a constant and var to make a variable。一个常量的值在编译时不需要知道,但你必须一次赋值(The value of a constant doesn’t need to be kNown at compile time,but you must assign it a value exactly once.)
eg1:
- var myVariable = "The width is "
- myVariable = 50
- let myConstant = 42
- 在上面的eg1中,我们的变量myVariable并没有明确的给他一个数据类型,常量myConstant也是没有明确的给它一个数据类型。因为编译器会根据我们给的初始值区推断我们的常量或是变量是什么类型的数据。但是一个常量或是一个变量必须有一个同一类型的值。
- A constant or variable must have the same type as the value you want to assign to it. However,you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above,the compiler infers that myVariable is an integer because its initial value is an integer.
但是在声明变量的时候,我们也可以这样给它一个明确的数据类型
eg2:
var welcomeMessage:String
“Declare a variable called welcomeMessage that is of type String.”
The welcomeMessage variable can Now be set to any string value without error:
- welcomeMessage = "Hello"
2.什么时候使用常量和变量
NOTE
If a stored value in your code is not going to change,always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.
简单翻译就是在代码中需要改变的使用变量,不需要改变的使用常量。
eg3:
You can change the value of an existing variable to another value of a compatible type. In this example,the value of friendlyWelcome is changed from "Hello!" to "Bonjour!”:(简短理解就是,变量是可以修改的)
- var friendlyWelcome = "Hello!"
- friendlyWelcome = "Bonjour!"
- // friendlyWelcome is Now "Bonjour!"
Unlike a variable,the value of a constant cannot be changed once it is set. (常量声明后就不能改变)Attempting to do so is reported as an error when your code is compiled:
- let languageName = "Swift"
- languageName = "Swift++"
- // this is a compile-time error - languageName cannot be changed
3.常量与变量的命名规则
Constant and variable names can contain almost any character,including Unicode characters:
- let π = 3.14159
- let 你好 = "你好世界"
- let
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。