国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > iOS > 正文

IOS  Swift基礎(chǔ)之switch用法詳解

2020-07-26 02:55:30
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

IOS  Swift基礎(chǔ)之switch用法詳解

概述

Swift中的switch語(yǔ)句與Java等語(yǔ)言中的switch有很大的相似點(diǎn),但是也有不同的地方,并且更加靈活。

Swift中switch的case語(yǔ)句中不需要添加break

Swift中需要考慮所有情況,default是必要的。

case分支可以添加多個(gè)條件,用,分割

case不局限與常量,可以使使用范圍

switch里可以使用元組

switch默認(rèn)不需要添加break,執(zhí)行一個(gè)case之后就跳出語(yǔ)句,如果想要繼續(xù)下面的語(yǔ)句可以使用fallthrough,但是fallthrough是直接進(jìn)入下一個(gè)case的語(yǔ)句,不會(huì)進(jìn)行case的判斷。感覺(jué)這里好坑。

實(shí)例代碼

1、不需要break,case里多個(gè)值用,分割。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條件里用范圍表達(dá)式

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")   fallthroughcase 100:  print("Perfect!")default:  print("Error")}//輸出"Great/n""Perfect!/n"

總結(jié)

可以發(fā)現(xiàn),Swift中的switch更加靈活和簡(jiǎn)潔,使用switch可以方便的處理很多操作。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 渝中区| 南陵县| 延吉市| 边坝县| 昭觉县| 镇康县| 遵义市| 玉田县| 南阳市| 攀枝花市| 阿拉善盟| 新龙县| 鲁甸县| 乐至县| 溆浦县| 丰城市| 七台河市| 湖州市| 温宿县| 西林县| 抚远县| 文安县| 苍溪县| 女性| 武城县| 青神县| 时尚| 锡林浩特市| 肇州县| 神农架林区| 永兴县| 城口县| 会泽县| 保德县| 贵港市| 皋兰县| 万全县| 博客| 交口县| 新巴尔虎右旗| 疏附县|