标签:
Swift提供了多种流程控制结构,包括可以多次执行任务的while循环,基于特定条件选择执行不同代码分支的if、guard和switch语句,还有控制流程跳转到其他代码的break和continue语句。
Swift 还增加了for-in循环,用来更简单地遍历数组(array),字典(dictionary),区间(range),字符串(string)和其他序列类型。
Swift 的switch
语句比 C 语言中更加强大。在 C 语言中,如果某个 case 不小心漏写了break
,这个 case 就会贯穿至下一个 case,Swift 无需写break
,所以不会发生这种贯穿的情况。case 还可以匹配更多的类型模式。
for index in 1...5 { print("\(index) times 5 is \(index * 5)"); } //如果不需要知道区间序列内每一项的值,可以使用下划线(_)替代变量名来忽略对值的访问 for _ in 1...5 { print("Hello"); }
while循环运行一系列语句直到条件变成false。这类循环适合使用在第一次迭代前迭代次数未知的情况下。Swift 提供两种while循环形式:
var start = 0; let end = 10; var diceRoll = 0; while start < end { print(start); start += 1; } start = 0; repeat { print(start); start += 1; }while start < end
//IF let temperatureInFahrenheit = 90; if temperatureInFahrenheit <= 32 { print("It‘s very cold. Consider wearing a scarf."); } else if temperatureInFahrenheit >= 86 { print("It‘s really warm. Don‘t forget to wear sunscreen."); } else { print("It‘s not that cold. Wear a t-shirt."); } //Switch基础用法 let someCharacter: Character = "e"; switch someCharacter { case "a", "e", "i", "o", "u": print("\(someCharacter) is a vowel"); case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": print("\(someCharacter) is a consonant"); default: print("\(someCharacter) is not a vowel or a consonant"); } //说明: //1.不需要在 case 分支中显式地使用break语句 //2.一个 case 也可以包含多个模式,用逗号把它们分开; //3.每一个 case 分支都必须包含至少一条语句。 //Switch区间匹配 let approximateCount = 62; switch approximateCount { case 0: print("no"); case 1 ..< 5: print("a few"); case 5 ..< 12: print("several"); case 12 ..< 100: print("dozens"); case 100 ..< 1000: print("hundreds"); default: print("many"); } //Switch元组匹配 let somePoint = (1, 1); switch somePoint { case (0, 0): print("(0, 0) is at the origin"); case (let x, 0): //值绑定 print("(\(somePoint.0), 0) is on the x-axis, x value of \(x)"); case (0, _): print("(0, \(somePoint.1)) is on the y-axis"); case (-2...2, -2...2): print("(\(somePoint.0), \(somePoint.1)) is inside the box"); default: print("(\(somePoint.0), \(somePoint.1)) is outside of the box"); } //说明:使用下划线(_)来匹配所有可能的值
控制转移语句改变代码的执行顺序,通过它可以实现代码的跳转。Swift 有五种控制转移语句:
标签:
原文地址:http://www.cnblogs.com/LeeGof/p/5674162.html