Swift / Swift Basics
Control Structures
In this tutorial, we'll explore Swift's control flow structures which allow you to control the execution of code based on specific conditions.
Section overview
4 resourcesExplores the foundational concepts in Swift, including variables, data types, and operators.
1. Introduction
This tutorial aims to introduce the concept of control flow structures in Swift programming language. Control flow structures allow your program to execute specific blocks of code based on a given condition or loop. It's a key concept to understand as it gives your code more flexibility and power.
By the end of this tutorial, you will learn about:
- If, Else If, and Else statements
- For and While loops
- Switch statements
Prerequisites: Basic understanding of Swift syntax and data types.
2. Step-by-Step Guide
If, Else If, Else Statements
An if statement checks whether a condition is true. If the condition is true, the code within the if statement is executed. If the condition is false, the code is skipped.
An else if statement follows an if or another else if statement and contains an additional condition that is checked if all preceding conditions are false.
An else statement follows an if or else if statement and is executed if all preceding conditions are false.
// If statement
var temperature = 20
if temperature < 30 {
print("It's not too hot today.")
}
// Else If statement
var weather = "rainy"
if weather == "sunny" {
print("It's a beautiful day.")
} else if weather == "rainy" {
print("Don't forget your umbrella.")
}
// Else statement
var isSunny = false
if isSunny {
print("It's a beautiful day.")
} else {
print("It's cloudy.")
}
For and While Loops
A for loop executes a block of code a specific number of times.
A while loop executes a block of code as long as a condition is true.
// For loop
for i in 1...3 {
print("Hello, Swift!")
}
// While loop
var number = 10
while number > 0 {
print(number)
number -= 1
}
Switch Statements
A switch statement checks a value and compares it against several possible matching patterns.
// Switch statement
var fruit = "apple"
switch fruit {
case "apple":
print("Red and delicious.")
case "banana":
print("Yellow and sweet.")
default:
print("Unknown fruit.")
}
3. Code Examples
Let's see these concepts in action with more detailed examples:
Example 1: If, Else If, Else Statements
var score = 85
if score >= 90 {
print("You got an A!")
} else if score >= 80 {
print("You got a B!")
} else if score >= 70 {
print("You got a C.")
} else {
print("Better luck next time.")
}
This code evaluates a student's score and prints a grade. If the score is 90 or higher, the student gets an A. If the score is less than 90 but 80 or higher, the student gets a B, and so on.
Example 2: For and While Loops
// For loop
for number in 1...5 {
print("Number is: \(number)")
}
This code prints numbers 1 through 5. It uses a for loop to iterate over a range.
// While loop
var count = 1
while count <= 5 {
print("Count is: \(count)")
count += 1
}
This code does the same thing as the previous example, but it uses a while loop.
Example 3: Switch Statements
var dayOfWeek = "Tuesday"
switch dayOfWeek {
case "Monday", "Wednesday", "Friday":
print("Gym day.")
case "Tuesday", "Thursday":
print("Rest day.")
default:
print("Free day.")
}
This code prints an activity based on the day of the week.
4. Summary
In this tutorial, we covered control flow structures in Swift, including if, else if, else statements, for and while loops, and switch statements. Control flow structures are a fundamental part of any programming language and provide flexibility in code execution.
Continuing to practice these concepts with different scenarios will lead to a better understanding. You can also explore more advanced topics like nested loops and switch statements with ranges.
5. Practice Exercises
Exercise 1: Write a Swift program that prints the multiplication table of 5 using a for loop.
Exercise 2: Write a Swift program that counts down from 10 to 1 using a while loop.
Exercise 3: Write a Swift program that categorizes a given number into "positive", "negative", or "zero" using a switch statement.
Solutions:
// Exercise 1
for i in 1...10 {
print("5 * \(i) = \(5 * i)")
}
// Exercise 2
var number = 10
while number > 0 {
print(number)
number -= 1
}
// Exercise 3
var number = 0
switch number {
case let x where x > 0:
print("Positive")
case let x where x < 0:
print("Negative")
default:
print("Zero")
}
Keep practicing these exercises with different inputs and scenarios to get a solid understanding of control flow structures in Swift. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article