IOS Swift基礎之switch用法詳解

網(wǎng)站建設哪家好,找成都創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、小程序開發(fā)、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了四川免費建站歡迎大家使用!
概述
Swift中的switch語句與Java等語言中的switch有很大的相似點,但是也有不同的地方,并且更加靈活。
Swift中switch的case語句中不需要添加break
Swift中需要考慮所有情況,default是必要的。
case分支可以添加多個條件,用,分割
case不局限與常量,可以使使用范圍
switch里可以使用元組
switch默認不需要添加break,執(zhí)行一個case之后就跳出語句,如果想要繼續(xù)下面的語句可以使用fallthrough,但是fallthrough是直接進入下一個case的語句,不會進行case的判斷。感覺這里好坑。
實例代碼
1、不需要break,case里多個值用,分割。default不能省略
let name = "yangqiangyu"
switch name{
case "yangqiangyu","yqy":
print("This is my name")
default:
print("This is not my name");
}
//"This is my name\n"
2、case條件里用范圍表達式
let score = 90;
switch score{
case 0:
print("you got an egg")
case 1..<60:
print("you failed")
case 60:
print("Just passed")
case 61..<80:
print("Just so so")
case 80..<90:
print("Good")
case 90..<100:
print("Great")
case 100:
print("Perfect!")
default:
print("Error")
}
//輸出結(jié)果:"Great\n"
3、switch使用元組
let point:(x:Int,y:Int) = (x:1,y:1)
switch point{
case (0,0):
print("It's a origin")
case (_,0)://忽略point中的x值
print("It's on x-axis.")
case (0,_)://忽略point中的y值
print("It's on y-axis")
default:
print("It's just an ordinary point")
break
}
//輸出結(jié)果:
"It's just an ordinary point\n"
4.switch中的case中需要使用元組中的值
let point2 = (8,0)
switch point2{
case (0,0):
print("It's a origin")
case (let x,0)://賦值給x
print("It's on x-axis.")
print("The x value is \(x)")
case (0,let y)://賦值給y
print("It's on y-axis")
print("The y value is \(y)")
case (let x,let y):
print("The x value is \(x)")
print("The y value is \(y)")
}
//輸出結(jié)果:
"It's on x-axis.\n"
"The x value is 8\n"
5.fallthrough使用
let score = 90;
switch score{
case 0:
print("you got an egg")
case 1..<60:
print("you failed")
case 60:
print("Just passed")
case 61..<80:
print("Just so so")
case 80..<90:
print("Good")
case 90..<100:
print("Great")
fallthrough
case 100:
print("Perfect!")
default:
print("Error")
}
//輸出
"Great\n"
"Perfect!\n"
總結(jié)
可以發(fā)現(xiàn),Swift中的switch更加靈活和簡潔,使用switch可以方便的處理很多操作。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
文章名稱:IOS Swift基礎之switch用法詳解
標題網(wǎng)址:http://www.chinadenli.net/article32/pgeosc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、軟件開發(fā)、動態(tài)網(wǎng)站、Google、自適應網(wǎng)站、域名注冊
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)