1 //: Playground - noun: a place where people can play 2 3 import UIKit 4 5 6 //1.if语句实现条件选择 7 //(1)单分支 8 var age = 9 9 10 if age < 10 { 11 12 print("年龄小于10岁") 13 } 14 15 //(2)双分支 16 var oranges = 20 17 var apples = 30 18 19 if oranges < apples { 20 21 print("苹果多") 22 } else { 23 24 print("桔子多") 25 } 26 27 28 //(3)多分支 29 var score = 65 30 var grade : Character; 31 32 if score >= 90 { 33 grade = "A" 34 } else if score >= 80 { 35 36 grade = "B" 37 } else if score >= 70 { 38 39 grade = "C" 40 } else if score >= 60 { 41 42 grade = "D" 43 } else { 44 grade = "F" 45 } 46 47 print("grade=(grade)") 48 49 50 //2. switch语句实现条件选择 51 /* 52 (1)switch后面的表达式可以整型,浮点型,字符,字符串,数值可以是单个的,也可以是一段范围 53 (2)case分支不需要加break语句,分支执行完毕以后会自动的跳出switch 54 (3)必须有default,必须放在所有分支的最后面 55 (4)每个case必须有至少一条语句,如果想匹配多个条件,可以用一个case将多个条件用逗号隔开 56 57 */ 58 var light = "Green" 59 60 switch light { 61 62 case "Red": 63 print("停") 64 case "Yellow","Green": 65 print("注意小心通过") 66 default: 67 print("灯坏了") 68 69 } 70 71 switch score { 72 case 90...100: //[90,100] 73 grade = "A" 74 case 80..<90: //[80,90) 75 grade = "B" 76 case 70..<80: 77 grade = "C" 78 case 60..<70: 79 grade = "D" 80 default: 81 grade = "F" 82 83 } 84 85 //3.while和do while 86 var j = 10; 87 88 repeat { 89 print(j) 90 j-- 91 92 93 } while j > 0 94 95 //4. for循环 96 //当循环体中的操作与循环变量无关时,循环变量可以用_代替 97 for _ in 0...10 { 98 print("next") 99 100 } 101 102 //5.控制转移语句 103 //(1)break和continue 104 for k in 0..<10 { 105 if k == 3 { 106 continue; 107 } 108 109 print(k) 110 } 111 112 //(2)fallthrough:用于switch语句中多个条件的混合处理 113 let intergerToDescribe = 5 114 115 var description = "The number (intergerToDescribe) is" 116 117 switch intergerToDescribe { 118 case 2,3,5,7,11,13,17,19: 119 description += " a prime number, and also" 120 fallthrough 121 default: 122 description += " an integer" 123 124 125 } 126 127 print(description) 128 129 //(3)标签:用于复杂的循环处理,用标签来进行标识流程控制 130 label1:for var x = 0; x < 5; x++ { 131 for var y = 5; y > 0; y-- { 132 133 if y == x { 134 break label1; 135 } 136 137 print("(x,y)=((x),(y))") 138 139 } 140 141 142 143 144 }