0
0
Swiftprogramming~5 mins

If and if-else statements in Swift

Choose your learning style9 modes available
Introduction

If and if-else statements help your program make choices. They let your code do different things based on conditions.

To check if a number is positive or negative.
To decide what message to show based on user input.
To run some code only if a condition is true.
To choose between two actions depending on a test.
To handle simple decision-making in your app.
Syntax
Swift
if condition {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
The condition must be a Boolean expression (true or false).
The else part is optional; you can use just if without else.
Examples
This checks if number is greater than zero and prints a message if true.
Swift
let number = 10
if number > 0 {
    print("Number is positive")
}
This prints "Positive" if number is above zero, otherwise it prints "Not positive".
Swift
let number = -5
if number > 0 {
    print("Positive")
} else {
    print("Not positive")
}
This decides voting eligibility based on age.
Swift
let age = 18
if age >= 18 {
    print("You can vote")
} else {
    print("You cannot vote yet")
}
Sample Program

This program checks the temperature and prints if it is hot or not.

Swift
let temperature = 30
if temperature > 25 {
    print("It's hot outside")
} else {
    print("It's not hot outside")
}
OutputSuccess
Important Notes

Always use curly braces { } even for single lines to avoid mistakes.

Conditions must be Boolean expressions, like comparisons (==, >, <).

Summary

If statements let your program choose actions based on conditions.

If-else statements provide two paths: one if true, another if false.

Use them to make your code respond to different situations.