Swift 基础知识
一、常量与变量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:
但是在声明变量的时候,我们也可以这样给它一个明确的数据类型 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:
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!”:(简短理解就是,变量是可以修改的)
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:
3.常量与变量的命名规则Constant and variable names can contain almost any character,including Unicode characters:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |