3流程控制

##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
	}
}
相關文章
相關標籤/搜索