O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required