本篇作为Swift的第一篇,主要简述Swift中的基础数据类型
let声明常量,常量在初次赋值后不能再被改变var声明常量,常量在初次赋值后可以被更改
let pi: Double = 3.14159
var variableNumber: Int = 1_000__000
注:Swift中可以用下划线_分隔大数字,增加人类可读性,数量和位置随意。
下划线 _ 还有占位符的作用,代表忽略该项,后面会用到
Int(doubleNumber)var integer: Int = 100
var decimal: Double = 12.5
var sum = integer + Int(decimal)
.访问元组中的元素,如果没有指定索引值,则默认为从0开始的数字索引
//默认索引值的元组,从0开始
let coordinates: (Double, Int) = (2.1, 3)
let x: Int = coordinates.0
let y: Int = coordinates.1
//定义索引值的元组
let coordinates3D: (x: Int, y: Int, z: Int) = (2, 3, 1)
let x: Int = coordinates3D.x
let y: Int = coordinates3D.y
let z: Int = coordinates3D.z
let (x, y, z) = coordinates3D //同上三句
let typeInferredInt = 10
+ - * / % << >> += -=……== != > < >= <=……Bool)及逻辑操作符:&& || !()设定操作优先级
let add = 2 + 6
let subtract = 10 - 2
let multiply = 2 * 4
let divide = 24 / 3
let modulo = 11.6 % 1.2 //0.8 Swift可以对小数求余
let shiftLeft = 1 << 3 //位移操作将十进制数的二进制形式位移后再返回十进制结果
Character类型存储单一字符,String类型用来存储一串字符+ += 可以用来连接多个字符串\(插入内容)插入内容== 符可以用作字符串判等,> < 用作字符串比较时依据字母表序位置先后判断结果
let message: String = "Hello"
let exclamationMark: Character = "!"
let sentence = message + String(exclamationMark) //"Hello!"
let name = "Qiao"
let sayHi = "Hello my name is \(name)!"
let guess = "dog"
let dogEqualsCat = guess == "cat" //false
let order = "cat" < "dog" //true
if if - else if - else if - else(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>switch <CONDITION> case: case: default:let-where 语法
let number = 10
switch (number) {
case let x where x % 2 == 0:
print("Even")
default:
print("Odd")
}
//部分匹配(partial matching)
let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)
switch (coordinates) {
case (0, 0, 0): // 1
print("Origin")
case (_, 0, 0): // 2
print("On the x-axis.")
case (0, _, 0): // 3
print("On the y-axis.")
case (0, 0, _): // 4
print("On the z-axis.")
default: // 5
print("Somewhere in space")
}
//保留对应值的部分匹配
let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)
switch (coordinates) {
case (0, 0, 0):
print("Origin")
case (let x, 0, 0):
print("On the x-axis at x = \(x)")
case (0, let y, 0):
print("On the y-axis at y = \(y)")
case (0, 0, let z):
print("On the z-axis at z = \(z)")
case (let x, let y, let z):
print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}
let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)
switch (coordinates) {
case (let x, let y, _) where y == x:
print("Along the y = x line.")
case (let x, let y, _) where y == x * x:
print("Along the y = x^2 line.")
default:
break
}
.....<
let closedRange = 0...5 //范围从0到5,包括5
let halfOpenRange = 0..<5 //范围从0到4,不包括5
for-inwhilerepeat-while:类似于其他语言的do-whilebreak 退出循环, continue 继续下一次循环continue 配合使用,可以使程序跳到指定语句,
类似C中的 goto
//for循环
for <VARIABLE> in <RANGE> {
<LOOP CODE>
}
//while循环
while <CONDITION> {
<LOOP CODE>
}
//repeat-while循环
repeat {
<LOOP CODE>
} while <CONDITION>
//标签语句
var sum = 0
rowLoop: for row in 0..<8 {
columnLoop: for column in 0..<8 {
if row == column {
continue rowLoop
}
sum += row*column
}
}
func 关键字声明函数-> 接在函数声明后面,可以返回元组inout 关键字,
声明为引用传参的函数在调用时参数前要加 &,以指明这是引用方式var function: (Int, Int) -> Int
func 函数名(第一个参数标签: 参数类型, 指定的参数外部标签 参数标签: 参数类型 = 参数默认值) -> 函数返回值 {
函数体
return 返回值
}
//闭包声明
var multiplyClosure: (Int, Int) -> Int //和函数类型的变量基本一致
//闭包赋值
multiplyClosure = { (a: Int, b: Int) -> Int in
return a * b
}
//闭包使用
let result = multiplyClosure(4, 2) //result=8
//闭包简化语法
//如果只有一句表达式,可以省略return
//利用类型推倒机制,在已经声明过的前提下可以省略返回类型和参数类型
//参数列表:参数可以用从0开始的序列引用
multiplyClosure = {
$0 * $1
}
//尾闭包语法(trailing closure syntax)
//当一个闭包作为函数的最后一个参数时, 尾闭包可以化简代码
//原来
operateOnNumber(4, 2, operation: {
$0 + $1
})
//尾闭包
operateOnNumber(4, 2) {
$0 + $1
})
? 声明:var errorCode: Int?! 跟在可选类型变量后。一般不推荐这种做法,
强制拆包会,如果值为空,可能会引起运行时crashif let binding:这种方式较为安全的存取Optional?? 指定默认值
//一次拆包多个值
let authorName: String? = "Qiao"
let authorAge: Int? = 30
if let name: String = authorName,
age: Int = authorAge {
print("The author is \(name) who is \(age) years old.")
} else {
print("No author or no age.")
}
//nil coalescing
var result: Int = optionalInt ?? 0