Conditional code execution with the if...else statement

The if...else statement will check a conditional statement and, if it is true, it will execute a block of code. If the conditional statement is not true, it will execute a separate block of code. This statement follows this format:

if condition { 
  block of code if true 
} else { 
  block of code if not true 
} 

Let's modify the preceding example to use the if...else statement to tell the user which team won:

 
let teamOneScore = 7  
let teamTwoScore = 6 
if teamOneScore>teamTwoScore{  
  print("Team One Won") 
} else { 
  print("Team Two Won") 
} 

This new version will print out Team One Won if the value of teamOneScore is greater than the value of teamTwoScore; otherwise, it will print out the message, Team Two Won. This fixed one problem with our code, but what do you think the code will do if the value of teamOneScore is equal to the value of teamTwoScore? In the real world, we would see a tie, but in the preceding code, we would print out Team Two Won, which would not be fair to team one. In cases like this, we can use multiple else if statements and an else statement at the end to act as the default path if no conditional statements are met.

The following code sample illustrates this:

let teamOneScore = 7  
let teamTwoScore = 6 
if teamOneScore>teamTwoScore { 
  print("Team One Won") 
} else if teamTwoScore>teamOneScore {  
  print("Team Two Won") 
} else { 
  print("We have a tie") 
} 

In the preceding code, if the value of teamOneScore is greater than the value of teamTwoScore, we print Team One Won to the console. We then have an else if statement, which means the conditional statement is checked only if the first if statement returns false. Finally, if both of the if statements return false, the code in the else block is called and We have a tie is printed to the console.

This is a good time to point out that it is not good practice to have numerous else if statements stacked up, as we showed you in the previous example. It is better to use the switch statement, which we will look at later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset