Swift Conditional Statements (If, If-Else, Ternary) Example

1. Introduction

In Swift, conditional statements allow developers to execute different pieces of code based on specific conditions. This flexibility enables programmers to create dynamic behavior in their applications. We'll cover the if, if-else, and the ternary conditional operator in this example.

2. Source Code Example

// The 'if' statement
var age = 18
if age >= 18 {
    print("You are an adult!")
}

// The 'if-else' statement
var score = 75
if score >= 50 {
    print("You passed!")
} else {
    print("You failed!")
}

// The ternary conditional operator
let hasTicket = true
let admissionPrice = hasTicket ? "10 dollars" : "20 dollars"
print("You need to pay \(admissionPrice)")

Output:

You are an adult!
You passed!
You need to pay 10 dollars

3. Step By Step Explanation

1. The if Statement:

- This is the simplest form of a conditional statement. It executes a block of code only if a particular condition is true.

- In our example, we've set the age to 18. The if statement checks whether the age is 18 or above. If the condition is true, it prints "You are an adult!".

2. The if-else Statement:

- This form of conditional statement allows two different blocks of code to be executed based on whether a condition is true or false.

- We set the score to 75. The if part of the statement checks if the score is 50 or above. If the condition is true, it prints "You passed!". Otherwise, the else part executes and prints "You failed!".

3. The Ternary Conditional Operator (? :):

- This is a concise way of writing a conditional statement that involves two outcomes based on one condition.

- In our case, the condition checks if hasTicket is true. If true, the value before the colon ("10 dollars") is assigned to admissionPrice, otherwise, the value after the colon ("20 dollars") is assigned.

- The print statement then displays the appropriate admission price. 

In summary, conditional statements in Swift enable you to create logic in your applications, allowing for dynamic behavior based on various conditions. The choice between these forms will depend on the specific requirements of the task and how concise or readable you want your code to be.


Comments