##3.1 for 循环 ###for - in 循环结构swift
for loopVariable in startNumber ...endNumber
“...”告诉Swift起始数字和结束数字指定的是范围数组
1> var loopCounter : Int = 0 loopCounter: Int = 0 2> for loopCounter in 1...5{ 3. print("\(loopCounter)times \(loopCounter * loopCounter)") 4. } 1times 1 2times 4 3times 9 4times 16 5times 25
###另外一种指定范围语法"..<"app
8> for loopCounter in 1..<5 { 9. print("\(loopCounter)times \(loopCounter * loopCounter)") 10. } 1times 1 2times 4 3times 9 4times 16
"..<"比结束数字小1,用做数组索引时比较直观(由于数组索引从0开始)ide
###老式 for 循环 Swift3.0中去掉 须要stride方法的协助oop
13> for i in stride (from:10 ,through: 0 , by: -1) { 14. print("\(i)") 15. } 10 9 8 7 6 5 4 3 2 1 0
reversed反转code
16> for i in (0...10).reversed() { 17. print("\(i)") 18. } 10 9 8 7 6 5 4 3 2 1 0
###简写orm
19> var anotherLoopCounter = 3 anotherLoopCounter: Int = 3 20> anotherLoopCounter += 2 21> anotherLoopCounter $R0: Int = 5 22> anotherLoopCounter -= 3 23> anotherLoopCounter $R1: Int = 2 24> anotherLoopCounter++ error: repl.swift:24:19: error: '++' is unavailable: it has been removed in Swift 3 anotherLoopCounter++ ^~ += 1
递增++,递减--,swift3.0移除 移除缘由参考http://swift.gg/2016/03/30/swift-qa-2016-03-30/索引
##3.2 if 语句rem
var trafficLight = "Greed" if trafficLight != "Greed" { print("Stop!") }else{ print("Go!") }
比较运算符 “==” 等于 “!=” 非等于 “>” 大于 “<” 小于 “>=” 大于等于 "<=" 小于等于字符串
比较字符串
let tree1 = "Oak" let tree2 = "Pecan" let tree3 = "Maple" let treeCompare1 = tree1 > tree2 let treeCompare2 = tree2 > tree3
###if ,else if
var treeArray = [tree1, tree2 , tree3] for tree in treeArray{ if tree == "Oak"{ print("Furniture") }else if tree == "Pecan"{ print("Pie") }else if tree == "Maple"{ print("Syrup") } }
##3.3switch 字符串做为判断
treeArray += ["Cherry"] treeArray += ["apple"] for tree in treeArray{ switch tree { case "Oak": print("Furniture") case "Pecan","Cherry": print("Pie") case "Maple": print("Syrup") default: print("Wood") } } Furniture Pie Syrup Pie Wood
通常数字作判断
var position = 7 switch position { case 1: print("\(position)st") case 2: print("\(position)nd") case 3: print("\(position)rd") case 4...9: print("\(position)th") default: print("Not coverd") } 7th
swift中移除OC中switch的break,判断匹配到的语句后直接跳出
##3.4while循环
var base = 2 var target = 100 var value = 0 while value < target { value += base; }
do-while 更换为repeat-while(第一次执行完,在判断是否继续执行while循环)
repeat{ value += base }while value < target
break提早结束循环
var speedLimit = 75 var carSpeed = 0 while (carSpeed < 100){ carSpeed += 1 switch carSpeed { case 0...30: print("low Speed\(carSpeed)") case 31...50: print("Normal Speed\(carSpeed)") case 51...75: print("Litter Faset\(carSpeed)") default: print("Too Fast must Stop") } //break 提早结束循环 if(carSpeed > speedLimit){ break } }