Understanding Swift If-Statement


Introduction

An if statement is a fundamental control structure in Swift that allows conditional execution of code. It evaluates a Boolean expression, and if the condition is true, the associated block of statements executes. Otherwise, the program continues with the next statement after the if block.

These statements are crucial for decision-making in programming, enabling dynamic responses based on varying conditions.




Real-World Example

Imagine a teacher instructing students, "You can only write with a black pencil." The condition here is the use of a black pencil.

  • If black pencil = true, students can write.
  • Otherwise, they cannot write.


Syntax

Here’s the general syntax of an if statement in Swift:

if condition {
// Code executes if the condition is true
}

If the Boolean condition evaluates to true, the code inside the if block runs. Otherwise, the program moves on to the next statement after the block.



Examples

Example 1: Checking if a Number is Less Than 20

This program checks whether a given number is less than 20.

import Foundation

var number: Int = 10

if number < 20 {
print("The number is less than 20")
}

print("The value of the number is \(number)")

Output

The number is less than 20
The value of the number is 10

Dictionary Representation:

let result = [
"number": 10,
"isLessThan20": true
]

Example 2: Checking Voting Eligibility

A program to verify if a person is eligible to vote based on age.

import Foundation

var age: Int = 19

if age >= 18 {
print("Eligible for voting")
}

print("A candidate whose age is 18+ is eligible for voting.")

Output

Eligible for voting
A candidate whose age is 18+ is eligible for voting.

Dictionary Representation:

let votingEligibility = [
"age": 19,
"isEligible": true
]

Example 3: Validating Username for Login

This program checks if the entered username matches the stored username.

import Foundation

let storedUsername = "input231"
let enteredUsername = "input231"

if storedUsername == enteredUsername {
print("Login successful")
}

let sumResult = 32 + 23
print("The sum of 32 and 23 is \(sumResult)")

Output

Login successful
The sum of 32 and 23 is 55

Swift - If... Else Statement

Introduction

The if-else statement is a fundamental control structure in Swift that allows you to execute different blocks of code based on a given condition. If the specified condition evaluates to true, the code inside the if block executes. Otherwise, the code inside the else block runs.

This is an essential tool for decision-making in Swift programming, enabling dynamic and flexible code execution.

Understanding If-Else with a Real-Life Example

Imagine you are at a grocery store, and your mother tells you:

  • If apples are on sale, buy apples.
  • Otherwise, buy grapes.

In this scenario:

  • The condition is whether apples are on sale (if condition).
  • If apples are available at a discount, you purchase them.
  • Otherwise, you buy grapes (else condition).

This logic is precisely how an if-else statement functions in Swift.

Syntax

Below is the basic syntax of the if-else statement:

if condition {
// Code executes when condition is true
} else {
// Code executes when condition is false
}

When the Boolean expression evaluates to true, the if block runs. Otherwise, the else block executes.

Example 1: Checking a Condition in Swift

Swift Program to Compare a Number

import Foundation

var number: Int = 100

if number < 50 {
print("The number is less than 50.")
} else {
print("The number is 50 or greater.")
}

print("The given number is \(number)")

Output

The number is 50 or greater.
The given number is 100

Explanation:

  • The program checks if number is less than 50.
  • Since 100 is greater than 50, the else block executes.



Example 2: Checking Even or Odd Numbers

Swift Program to Determine Even or Odd

import Foundation

let number = 41
let result: [String: String] = ["even": "Entered number is even.", "odd": "Entered number is odd."]

if number % 2 == 0 {
print(result["even"]!)
} else {
print(result["odd"]!)
}

Output

Entered number is odd.

Explanation:

  • The program checks if the number is divisible by 2.
  • If number % 2 == 0, it prints "Entered number is even."
  • Otherwise, it prints "Entered number is odd."



Example 3: User Authentication

Swift Program to Validate Username

import Foundation

let storedUsername = "SwiftCoder"
let enteredUsername = "SwiftCoder"

let messages: [String: String] = [
"success": "Login successful!",
"failure": "Invalid username. Please try again."
]

if storedUsername == enteredUsername {
print(messages["success"]!)
} else {
print(messages["failure"]!)
}

Output

Login successful!

Explanation:

  • The program checks if enteredUsername matches storedUsername.
  • If they match, it prints "Login successful!"
  • Otherwise, it prints "Invalid username. Please try again."