OneBite.Dev - Coding blog in a bite size

Use If Conditional Statement In Swift

Code snippet for how to Use If Conditional Statement In Swift with sample and detail explanation

In the world of coding, conditional statements are essential to control flow. Swift programming language is not an exception to this universal standard. In this article, we will discuss how to use the ‘If’ conditional statement in Swift.

Code Snippet: If Statement in Swift

Here is a simple swift code snippet that demonstrates the use of if conditional statement:

var temperature = 30

if temperature < 20 {
    print("It's cold! Warm up!")
} else if temperature > 30 {
    print("It's too hot! Cool down!")
} else {
    print("The weather is just right.")
}

Code Explanation: If Statement in Swift

Understanding how the ‘If’ conditional functions is a key part of any Swift program. Let’s break down the above code:

  • First, we declare a variable called ‘temperature’ and set its value to ‘30’.
var temperature = 30
  • Then, we craft our if statement. This begins with the keyword ‘if’, followed by our condition ‘temperature < 20’. Essentially, this code is checking if the value of ‘temperature’ is less than 20.
if temperature < 20
  • The condition is followed by a block of code enclosed in parentheses. This block is executed if the above condition of ‘temperature < 20’ is true. In our case, the program will print “It’s cold! Warm up!” to the console.
{
 print("It's cold! Warm up!")
}
  • After the first condition and its block of code, we can add an optional ‘else if’ condition. The code checks if ‘temperature’ is greater than 30. If this condition is met, “It’s too hot! Cool down!” will be printed.
else if temperature > 30 
{
   print("It's too hot! Cool down!")
}
  • Finally, we conclude with an ‘else’ statement that acts as the default action when none of the above conditions is met. The program will print “The weather is just right.” to the console.
else {
   print("The weather is just right.")
}

This step by step explanation should guide you on how to use ‘If’ conditional statement in Swift. You can now control your program flow based on the value of your variables effectively. Happy Coding!

swift