分支语句
1. 条件语句 if-else ,基本的语法形式例如以下。当中 “[]” 中 的部分能够省略。
if boolean-expression {
statement1;
} [else if boolean-expression {
statement2;
} ] [else {
statement3;
} ]
实例:
var number1 = 0;
var number2 = 1;
var max = 0;
if number1 >number2 {
max = number1;
} else if number1 < number2 {
max = number2;
} else {
max = number1;
}
println("Themaximum is \(max)")
2 .多分支语句 switch 它的语法形式例如以下:
switch some value to consider {
case value 1:
respond to value 1 case value 2, value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
每一个 case 不须要显式地加入 break ,每一个 case 至少有 一条语句。
能够比較不论什么类型。
实例1:
let count = 3_000
let countedThings = "stars inthe Milky Way"varnaturalCount: String
switch count {
case 0:
naturalCount ="no" case 1...3:
naturalCount ="a few" case 4...9:
naturalCount ="several"
case 10...99:
naturalCount ="tens of" case 100...999:
naturalCount ="hundreds of" case 1000...999_999:
naturalCount ="thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
循环语句
while语句
do-while语句
for语句
for in语句
while 循环
while condition{
statements
}
vari = 100 varr = 0 vars= 0 vart = 0
while i < 1000 {
r= i / 100
s=( i - r* 100 ) / 10
t= i - r* 100 - s* 10
if( i == r * r* r + s* s *s + t* t * t){
println ( "i = \(i)" )
}
i++
}
do while 循环
do {
statements
} while condition
vari = 100 varr = 0 vars= 0 vart = 0
do {
r= i / 100
s=( i - r* 100 ) / 10
t= i - r* 100 - s* 10
if( i == r * r* r + s* s *s + t* t * t){
println ("i = \(i)" )
}
i++
} while i < 1000
for initialization; condition; increment {
statements
}
vari= 8 varr = 0 vars= 0
forvarj =0; j <=i; j++{
r = j * j
s=j * j * j
println (" 整数为 :\(j) ");
println (" 相应的平方和 :\( r)")
println ( " 相应的立方和 : \( s ) " )
}
for in 循环
用于遍历集合。
1. 遍历范围
forindex in1...5{
println( " \(index) times 5 is \(index * 5 )" )
}
2. 忽略循环变量
letbase = 3
letpower = 10 varanswer = 1
for_ in 1...power {
answer *=base
}
println (" \(base )to the power of \(power )is \(answer ) " )
5 .遍历字符串
1.12.3 跳转语句
• continue
• break
• fallthrough
• return
1.continue 实例:
for var i = 0; i < 100; i++ {
if i % 10 == 0 {
continue;
}
println("i = \(i)");
}
2. break 实例:
for var i = 0; i < 10;i++ {
if i == 3 {
break;
}
println("i = \(i)");
}
println("Game Over!");
3. fallthrough 实例:
let integerToDescribe = 5
var description = "Thenumber \(integerToDescribe) is"
switchintegerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"fallthrough
default:
description += " an integer."
}
println(description)
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎加入Swift技术交流群:362298485
请发表评论