- 使用 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 支持浮點數(shù)的求余運算
let x = 12.5
let y = 2.4
x%y
- Swift 支持區(qū)間運算符:閉區(qū)間和前閉后開區(qū)間
for index in 1...10
{
print(index)
}
for index in 1..<10
{
print(index)
}
- Swift 的switch語句
- 每個case不需要break
- 可以在一個case中添加多個條件
- 支持不止整形的case比較,包括所有基本類型的數(shù)據(jù)
- 必須覆蓋所有可能的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語句支持區(qū)間,支持元組,如果要跳到下一個使用fallthrough 關(guān)鍵字阎曹,注意煞檩,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("就是一個點而已")
}
- 可以給一個循環(huán)一個名字,然后使用控制轉(zhuǎn)移關(guān)鍵字:break和continue 直接操作這個循環(huán)斟湃,類似goto語句
//直接跳出最外層的循環(huán)
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 關(guān)鍵字, 主要用于代碼風格的確立檐薯,Apple 提倡先剔除無關(guān)的邏輯凝赛,專注于函數(shù)本身的業(yè)務(wù)
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")
}