加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 基础知识

发布时间:2020-12-14 02:37:47 所属栏目:百科 来源:网络整理
导读:一、常量与变量 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 compi

一、常量与变量

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读