《浅入浅出Swift》ControlFlow 控制语句

####Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

//for
for var index=0;index<3;++index{
println("index is \(index)")
}
//or
var index :Int
for index = 0; index<3;++index{
println("index is \(index)")
}

//条件语句if else
let individualScores = [75,43,103,87,12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
}else{
teamScore += 1
}
}
println("score \(teamScore)")

//while
var count = 0
var whileIndex = 10

while whileIndex > 0 {
count += whileIndex
// println("count \(count)")//10+9+8+7+6+5+4+3+2+1=55
// println("whileIndex \(whileIndex)")
--whileIndex
}
println("count = \(count)")
//or
do {
count+=whileIndex
--whileIndex
}while whileIndex > 0
println("do count = \(count)")

//switch
let someCharacter:Character = "e"
switch someCharacter{
case "a","e","i","o","u":
println("\(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":
println("\(someCharacter) is a consonant")
default:
println("\(someCharacter) is not a vowel or a consonant")
}

let countSwitch = 15
switch countSwitch{
case 0:println("countSwitch count is 0")
case 1...10:println("countSwitch count is 1...10")
case 11...20:println("countSwitch count is 11...20")//get
default:println("什么都不是")
}

//元组switch
let myPoint = (1,3)
switch myPoint {
case (0,0):println("myPoint is (0,0)")
case (_,0):println("myPoint 第二个元素为0 (_,0)")
case (1,_):println("myPoint 第一个元素为1 (1,_)")//get
default:println("myPoint 什么都不是")
}

//switch let
let myNewPoint = (2,0)
switch myNewPoint {
case (let x , 0): println("myNewPoint is x,0")//get
case (0, let y): println("myNewPoint is 0,y")
case let(x,y): println("myNewPoint is x,y");
}

//switch where
let myWherePoint = (1,-1)
switch myWherePoint {
case let (x,y) where x == y: println(" x==y")
case let (x,y) where x == -y: println(" x== -y")
case let (x,y):println("x,y")
}

//fallthrough
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is "
switch integerToDescribe{
case 2,5: description += "a prime number ,and also"
fallthrough
default :description += " an integer."
}
println(description)

Reference

坚持原创技术分享,您的支持将鼓励我继续创作!
0%