标签:des style class code http com
使用if和switch来创建流程条件,使用for-in、for、while、do-while来创建循环。条件和变量外面的小括号时可选的,但是循环体外面的大括号时必选的。
1 |
let individualScore=[75,43,103,87,12] |
2 |
var teamScore=0; |
3 |
for score in individualScore{ |
4 |
if (score>50){ |
5 |
teamScore+=3 |
6 |
} |
7 |
else { |
8 |
teamScore+=1; |
9 |
} |
10 |
} |
11 |
println( "\(teamScore)" ) |
在if语句中,条件必须时一个布尔型的表达式。
你可以通过if和let结合在一起来表达一些不明确的值。它说代表的值可以时一个确切的值也是可以时nil,可以通过变量类型后面跟上?的形式来表示。
1 |
var optionalName:String?= "lisen" ; |
2 |
//optionalName=nil; |
3 |
var greeting= "Hello" ; |
4 |
if let name=optionalName |
5 |
{ |
6 |
greeting= "Hello,\(name)" |
7 |
} |
8 |
println(greeting); |
Hello,lisen
Program ended with exit code: 0
Hello
Program ended with exit code: 0
switch语句支持任何数据(类型)并且更强大的比较操作
1 |
import Foundation |
2 |
3 |
let vegetable= "red pepper" |
4 |
switch vegetable{ |
5 |
case "celery" : |
6 |
println( "我靠,这个单词不认识" ); |
7 |
case let x where |
8 |
x.hasSuffix( "pepper" ): |
9 |
println( "有辣椒" ); |
10 |
default : |
11 |
println( "吃点啥都行" ) |
12 |
} |
有辣椒
Program ended with exit code: 0
1 |
import Foundation |
2 |
let interestingNumbers=[ |
3 |
"Prime" :[2,3,5,7,11,13], |
4 |
"Fibonacci" :[1,1,2,3,5,8], |
5 |
"Square" :[1,4,9,16,25], |
6 |
] |
7 |
var largest=0 |
8 |
for (kind,numbers) in |
9 |
interestingNumbers |
10 |
{ |
11 |
for number in numbers{ |
12 |
if (number>largest) |
13 |
{ |
14 |
largest=number; |
15 |
println(largest); |
16 |
} |
17 |
|
18 |
} |
19 |
} |
1
4
9
16
25
Program ended with exit code: 0
使用while语句执行重复的代码。
1 |
var n=2; |
2 |
while (n<=3){ |
3 |
println(n*2); |
4 |
n++; |
5 |
} |
1 |
import Foundation |
2 |
3 |
var n=2; |
4 |
do { |
5 |
println(n*2); |
6 |
n++; |
7 |
} while (n<=4) |
如下:
1 |
import Foundation |
2 |
3 |
//var firseForLoop=0; |
4 |
for i in 0..3{ |
5 |
println(i); |
6 |
} |
7 |
8 |
println( "***************************" ); |
9 |
for (var i=0;i<3;i++){ |
10 |
println(i); |
11 |
} |
标签:des style class code http com
原文地址:http://www.cnblogs.com/ilisen/p/3789302.html