04--swift之流程控制


1.forspa

var a = [1,2,3]orm

for e in a{字符串

print(e)it

}io

var dic = [1:"tom",2:"kite",3:"rose"]ast

for (key,value) in dic{margin

print("\(key):\(value)")top

}dict

for e in 1..<10{di

print(e)

}

2.while

var i = 1

var sum = 0

while i<=100{

sum += i

i++

}

print(sum)

//repeat while

var i = 1

var sum = 0

repeat{

sum += i

i++

}while i<=100

print(sum)

3.if else

var flag = true

if flag{

print("true")

}


var a = 1,b = 2

if a>b{

print(a)

}else{

print(b)

}

//if else if

var score = 90

if score>=90{

print("")

}else if score<90&&score>=80{

print("")


}else{

print("")

}

4.switch

條件能夠是整形以外的類型,如字符串

不用breakcase後面能夠有多個條件,必須有default,並且casedefault後面必須有語句

var diction = "east"

switch diction{

case "east":

print("east")

case "west":

print("west")

case "south":

print("south")

case "north":

print("north")

default:

print("default")

}

//case後面有多個條件

var direction = "up"

switch direction{

case "up","top","上面":

print("up")

case "down","bottom":

print("down")

default:

print("default")

}

//範圍匹配

var score = 90

switch score {

case 90...100:

print("very good")

case 80..<90:

print("good")

case 60..<80:

print("poor")

default:

print("default")

}

//switch值綁定

let point = (0,2)

switch point {

case (1,let y):

print("y=\(y)")

case (let x,2):

print("x=\(x)")

default:

print("default")

}

//case where

let point = (1,-1)

switch point {

case let (x,y) where x==y:

print("\(x),\(y) is x==y")

case let (x,y) where x == -y:

print("\(x),\(y) is x==-y")

default :

print("default")

}

相關文章
相關標籤/搜索