04--swift之流程控制

原创
2016/03/08 15:40
阅读数 2


1.for

var a = [1,2,3]

for e in a{

print(e)

}

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

for (key,value) in dic{

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

}

for e in 1..<10{

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")

}









展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部