Swift if-else語句
Swift的if-else語句包含兩個部分:if語句和else語句。愛掏網 - it200.com
如果測試評估為true,則執行if語句,如果測試評估為false,則執行else語句。愛掏網 - it200.com
語法
if expression {
// statements
} else {
// statements
}
示例
let number = 5
if number > 0 {
print("This is a positive number.")
} else {
print("This is not a positive number.")
}
print("This will be executed anyways.")
輸出:
This is a positive number.
This will be executed anyways.
在上述程序中,常數的值是正數(5),因此,測試用例的評估結果為真,并且if代碼塊內的語句被執行。愛掏網 - it200.com
讓我們將常數的值改為負數(-5),測試條件保持不變。愛掏網 - it200.com
let number = -5
if number > 0 {
print("This is a positive number.")
} else {
print("This is not a positive number.")
}
print("This will be executed anyways.")
輸出:
This is not a positive number.
This will be executed anyways.
您可以看到它執行了else代碼塊中的語句。愛掏網 - it200.com
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。