if語(yǔ)句基本使用
OC:
int age1 = 10;
int age2 = 20;
int max;
max = age2;
if (age1 > age2) {
max = age1;
}
NSLog(@"%d", max);
if (age1 > age2) {
max = age1;
} else {
max = age2;
}
NSLog(@"%d", max);
如果只有一條指令if后面的大括號(hào)可以省略
Swift:
if 條件表達(dá)式 {指令} if 條件表達(dá)式 {指令} else{指令}
0.if后的圓括號(hào)可以省略
1.只能以bool作為條件語(yǔ)句
2.如果只有1條指令if后面的大括號(hào)不可以省略
var age1:Int? = 10 // 10
var age2:Int? = 20 // 20
var max:Int? // nil
max = age2; // 20
if age1 > age2
{
max = age1;
}
else
{
max = age2; // 20
}
print(max) // "Optional(20)\n"
多分支
OC:
float score = 99.9;
if (score >= 90) {
NSLog(@"優(yōu)秀");
} else {
if (score >= 60) {
NSLog(@"良好");
} else {
NSLog(@"不給力");
}
}
if (score >= 90) {
NSLog(@"優(yōu)秀");
} else if (score >= 60) {
NSLog(@"良好");
} else {
NSLog(@"不給力");
}
swift:
var score = 99.9;
if score >= 90
{
print("優(yōu)秀")
}
else if score >= 60
{
print("良好")
}
else
{
print("不給力")
}