
上QQ阅读APP看书,第一时间看更新
The if statements – how to control the code flow
This is how we can branch our code logic based on some data stored in a variable:
let num = 5
if num % 2 == 0 {
print("The number \(num) is even.")
} else {
print("The number \(num) is odd.")
}
The general pattern of an if statement is organized as follows:
var logicalCheck = 7 > 5
if (logicalCheck) {
//code which will be executed if the logical check is evaluated to true
} else {
//code which will be executed if the logical check is evaluated to false
}
We know that the if clause gives us huge freedom to shape the code that will be executed (evaluated). An application may handle many different cases, but only the code that fulfills the conditions encoded in our solution will be triggered.