Using if statements

A basic if statement looks like this:

if condition {
code
}

The code in the curly braces is executed if the condition is true.

Let's implement an if statement now to see this in action: 

  1. Type in and run the following code:
// If statements execute code in curly braces if the condition is true
let isPictureVisible = true
// if the value is changed to false nothing would be printed
if isPictureVisible {
print("Picture is visible")
}

First, you created a constant, isPictureVisible, and assigned true to it. Next, you have an if statement that checks the value stored in isPictureVisible. Since the value is true, the print statement is executed and Picture is visible is printed in the Debug area.

  1. Try changing the value of isPictureVisible to false and run your code again. As the condition is now false, nothing will be printed.
  2. You can also execute statements if a condition is false. Type in and run the following code:
// isRestaurantFound == false returns true, so the print statement is executed
let isRestaurantFound = false
// if the value is changed to true nothing will be printed
if isRestaurantFound == false {
print("Restaurant was not found")
}

The constant isRestaurantFound is set to false. Next, the if statement is checked. The isRestaurantFound  == false condition returns true, and "Restaurant was not found" is printed in the Debug area. 

  1. Try changing the value of isRestaurantFound to true and run your code again. As the condition is now false, nothing will be printed.

What if you want to do one set of statements if a condition is true, and another set of statements if a condition is false? You use the else keyword.

  1. Type in and run the following code:
// if-else statement. Code after the else keyword is executed if the condition is false
let drinkingAgeLimit = 21
var customerAge = 19
// experiment by changing the customer age to a value greater than 21
if customerAge < drinkingAgeLimit {
print("Under age limit")
} else {
print("Over age limit")
}

Here, drinkingAgeLimit is assigned the value 21 and customerAge is assigned the value 19. In the if statement, customerAge < drinkingAgeLimit is checked. Since 19 < 21 returns true , Under age limit is printed in the Debug area.

If you change customerAge value to 22, customerAge < drinkingAgeLimit will return false, so Over age limit will be printed in the Debug area.

Up to now, you have only been dealing with single conditions. What if there are multiple conditions? That's where switch statements come in, and you will see them in the next section.

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

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