swift基礎(chǔ)-11-if

if語句基本使用
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后面的大括號可以省略

Swift:
if 條件表達(dá)式 {指令} if 條件表達(dá)式 {指令} else{指令}
0.if后的圓括號可以省略
1.只能以bool作為條件語句
2.如果只有1條指令if后面的大括號不可以省略

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("不給力")
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容