0%

Swift入门(基本概念)

常量&变量 Constants & Variables

常量:值一旦设置就不能改变
变量:值可以改变
示例代码:

1
2
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

同时可以申明多个常量或变量,示例如下:

1
2
let a = "g", b = "k", c = "d"
var x = 0.0, y = 0.0, z = 0.0

注意:

若值不会改变则申明常量,若会改变则申明变量

类型注解 Type Annotations

当申明常量和变量的时候可以提供一个类型注解,来明确它们值的类型
类型注解:(在常量或变量名后加)一个冒号、空格和要使用的类型名
示例代码:

1
var welcomeMessage: String

申明同一类型的多个常量或变量,可以共用一个类型注解,示例如下:

1
var red, green, blue: Double

注意:

Swift拥有强大的类型推断,因此如果常量或变量有初始值,则不需要写类型注解

常量和变量命名 Naming Constants and Variables

非法的命名:不能数字开头或包含空格字符、数学符号、箭头、私有Unicode标量值、线和框绘制字符

注意:

如果命名要与Swift关键字相同,则需要使用反引号(‘)包围该关键字,但最好避免这样命名

打印常量或变量 Printing Constants and Variables

方法如下:
print(_:separator:terminator:) function:
分隔符和终止符参数有默认值,因此可以在调用此函数时省略它们。默认情况下,函数通过添加换行符来终止它打印的行。

字符串插值 string interpolation
在print函数中,用括号括起常量或变量名字,在括号前面用反斜杠转义
示例代码:

1
2
3
let name = "abner"
print("My name is \(name)!")
// Prints "My name is abner!"

注释 Comment

单行注视:两个斜杠(//)

1
// This is a comment.

多行注释:以斜杠和星号(/)开始,星号和斜杠(/)结束

1
2
/* This is also a comment
but is written over multiple lines. */

嵌套多行注释:使您能够快速而轻松地注释掉大块代码,即使代码已经包含多行注释。

1
2
3
/* This is the start of the first multiline comment.
/* This is the second, nested multiline comment. */
This is the end of the first multiline comment. */

分号 Semicolons

Swift中不需要在每行末尾添加分号
但是在一行上写多个单独的语句时,需要分号分隔

整型 Integers

Swift提供8、16、32、64位的有符号或无符号整型

整型边界 Integer Bounds

调用整型的min或max方法可以获得整型的最小值或最大值
示例如下:

1
2
let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8

Int类型

在32位平台,Int的大小和Int32一致
在64位平台,Int的大小和Int64一致

UInt类型

在32位平台,UInt的大小和UInt32一致
在64位平台,UInt的大小和UInt64一致

注意:

除非需要UInt量级的数字,否则推荐使用Int,方便代码互相操作性

浮点数 Floating-Point Numbers

Swift 提供两种浮点数类型
Double:64位浮点数
Float:32位浮点数
Double至少精准到15位小数,Float至少精准到6位小数,当两者都可以使用时,推荐Double类型

类型安全和类型推断 Type Safety and Type Inference

类型安全:Swift是类型安全的,即要明确值的类型。Swift会在编译阶段进行类型检查来保证类型安全、
类型推断:Swift的类型推断使编译器在编译代码时可以自动推断出特定表达式的类型,只需检查提供的值即可

数字字面量 Numeric Literals

十进制浮点数:没有前缀
二进制浮点数:前缀为0b
八进制浮点数:前缀为0o
十六进制浮点数:前缀为0x

示例如下:

1
2
3
4
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation

十进制浮点数指数:E / e (可选)
十六进制浮点数指数:P / p (必须)
示例如下:

1
2
3
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0

无论是整型还是浮点数,都可以加入“0”或者“_”来帮助阅读
示例如下:

1
2
3
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1