IOS开发入门 Swift语法分支Switch语句使用详解

当知足前提时,执行某些操作,可以利用if-else来实现,也可以利用switch来实现,当前提分支较多的时辰且相对固定的时辰,switch语法形式更都雅一点

需要这些哦
Xcode
方式/
1Switch语法的最尺度写法如下:
     var value = https://vvvtt.com/article/2
     switch value {
         case 1: print("1"); break;
         case 2: print("2"); break;
         case 3: print("3"); break;
         default: print("others"); break;
     }

IOS开发入门 Swift语法分支Switch语句使用详解



2在Swift语法中,Switch语句中的分号,break都可以省略
     var value = https://vvvtt.com/article/3
     switch value {
         case 1: print("1")
         case 2: print("2")
         case 3: print("3")
         default: print("others")
     }

IOS开发入门 Swift语法分支Switch语句使用详解



3当知足两个或者多个case的时辰,执行不异的语句,可以这样写
     var value = https://vvvtt.com/article/2
     switch value {
         case 1, 2: print("1 或者 2")
         case 3: print("3")
         default: print("others")
【IOS开发入门 Swift语法分支Switch语句使用详解】     }

IOS开发入门 Swift语法分支Switch语句使用详解



4若是感觉这样归并case看起来不喜好的话,还可以这样分隔写
     var value = https://vvvtt.com/article/2
     switch value {
        case 1: fallthrough
        case 2: print("1 或者 2")
        case 3: print("3")
        default: print("others")
     }

IOS开发入门 Swift语法分支Switch语句使用详解



5若是去失落fallthrough关头字,编译器就会报错

IOS开发入门 Swift语法分支Switch语句使用详解



6Switch语句中的default分支是不克不及省略的,不然编译会报错

IOS开发入门 Swift语法分支Switch语句使用详解



7case后面除了数字之外,还可所以字符串
     var s = "Hello"
     switch s {
         case "Hello": print("Here is Hello")
         default: print("others")
     }

IOS开发入门 Swift语法分支Switch语句使用详解

猜你喜欢