- 使用 Int.max 可以知道该类型的最大值,同样还有Int.min Int8:max 等等
- 定义一个变量,可以加上"_"分隔符增加可读性,例如
var c = 1_000_000.00_00_1
等价于
var c = 1000000.00001
- 两个不同类型的变量不能直接运算,swift是强类型语言
let x:UInt8 = 12
let y:UInt16 = 13
let m = UInt16(x)+y
- if 语句后面的条件可以不用 括号,花括号不能省略,不能把 1作为if判断条件
let imTrue:Bool = true
let imFalse = false
if imTrue {
print("I am true")
}else{
print("I am false")
}
- 元组:tuple 可以存任意多个值,不同的值类型可以不同,可以使用下划线忽略分量
var point = (2,5)
var httpResponse = (404,"Not Found")
var point2:(Float,Float,Float) = (14,25.0,55.2)
//解包
var (x,y) = point
point.0
point.1
//其他方式
let point3 = (x:2,y:3)
point3.x
point3.y
let point4:(x:Int,y:Int) = (122,211)
point4.x
point4.y
- Swift 多行注释支持嵌套
- Swift 支持浮点数的求余运算
let x = 12.5
let y = 2.4
x%y
- Swift 支持区间运算符:闭区间和前闭后开区间
for index in 1...10
{
print(index)
}
for index in 1..<10
{
print(index)
}
- Swift 的switch语句
- 每个case不需要break
- 可以在一个case中添加多个条件
- 支持不止整形的case比较,包括所有基本类型的数据
- 必须覆盖所有可能的case,不能覆盖就使用default,default不能省略
- default 中不想干任何事情,可以加一个break,或者写() 当做一个空语句,不支持直接写“;”作为空语句
let rating = "a"
switch rating {
case "a","A":
print("Great");
case "b","B":
print("Just so so!")
case "c","C":
print("Bad")
default:
// break
()
}
- swich语句支持区间,支持元组,如果要跳到下一个使用fallthrough 关键字,注意,fallthrough 不会判断下一个条件符合不符合会直接进入下一个case
let point = (1,1)
switch point{
case (0,0):
print("在坐标原点")
fallthrough
case (_,0):
print("在x轴上")
fallthrough
case (0,_):
print("在y轴上")
case (-2...2,-2...2):
print("靠近坐标原点")
default:
print("就是一个点而已")
}
- 可以给一个循环一个名字,然后使用控制转移关键字:break和continue 直接操作这个循环,类似goto语句
//直接跳出最外层的循环
findAnswer:
for x in 1...300{
for y in 1...300{
if x*x*x*x + y*y == 15*x*y{
print(x,y)
break findAnswer
}
}
}
- switch中使用where条件
let point = (3,3)
switch point{
case let (x,y) where x == y:
print("It is on the line x=y")
case let (x,y) where x == -y:
print("It is on the line x = -y")
case let (x,y):
print("It is just a ordinary point")
}
- case 的用法
- if case
let age = 19
if case (10...19) = age where age >= 18{
print("You are a teenager and in a collage")
}
等价于
let age = 19
switch age{
case 10...19 where age >= 18:
print("You are a teenager and in a collage")
default:
break
}
- for case
for case let i in 1...100 where i%3 == 0{
print(i)
}
等价于
for i in 1...100{
if(i%3 == 0){
print(i)
}
}
- guard 关键字, 主要用于代码风格的确立,Apple 提倡先剔除无关的逻辑,专注于函数本身的业务
func buy( money:Int, price:Int, capacity:Int,volume:Int){
guard money >= price else{
return;
}
guard capacity >= volume else{
return
}
print("I can buy it")
}