0
0
Swiftprogramming~15 mins

Why Swift loops are safe by default - See It in Action

Choose your learning style9 modes available
Why Swift loops are safe by default
📖 Scenario: Imagine you have a list of daily temperatures and you want to check which days were warm. You will use a loop to go through the temperatures safely without errors.
🎯 Goal: Build a Swift program that uses a safe loop to check temperatures and print a message for warm days.
📋 What You'll Learn
Create an array called temperatures with exact values: 15, 22, 18, 30, 25
Create a variable called warmThreshold and set it to 20
Use a for loop with variable temp to iterate over temperatures
Inside the loop, use an if statement to check if temp is greater than warmThreshold
Print "Day with temperature X°C is warm." where X is the temperature
💡 Why This Matters
🌍 Real World
Checking temperature data safely is important in weather apps to avoid crashes and errors.
💼 Career
Understanding safe loops helps you write reliable Swift code for apps that handle lists and collections.
Progress0 / 4 steps
1
Create the temperature data
Create an array called temperatures with these exact values: 15, 22, 18, 30, 25
Swift
Need a hint?

Use let to create a constant array named temperatures with the given numbers.

2
Set the warm temperature threshold
Create a variable called warmThreshold and set it to 20
Swift
Need a hint?

Use let to create a constant named warmThreshold with value 20.

3
Loop through temperatures safely
Use a for loop with variable temp to iterate over temperatures. Inside the loop, use an if statement to check if temp is greater than warmThreshold
Swift
Need a hint?

Use for temp in temperatures to loop. Use if temp > warmThreshold inside the loop.

4
Print warm days
Inside the if statement, write print("Day with temperature \(temp)°C is warm.") to display the message
Swift
Need a hint?

Use print("Day with temperature \(temp)°C is warm.") inside the if block.