If Else Conditional Statement In Swift
Code snippet for how to If Else Conditional Statement In Swift with sample and detail explanation
Understanding the conditional logic is fundamental for any programming language, and Swift is no exception. The “If else” statement, a basic form of conditional statement, helps determine the flow of execution based on certain conditions.
Code Snippet for If Else Conditional Statement
We’ll begin by examining a brief snippet of Swift code that employs the “If else” construct:
var temperature = 28
if temperature < 20{
print("It's quite cold. Dress warmly!")
}
else if temperature > 30 {
print ("It's hot outside! Stay hydrated!")
}
else {
print ("The weather seems to be mild.")
}
Code Explanation for If Else Conditional Statement
The code above is an example of how “if else” conditional statement is used in Swift. The temperature
is our variable that holds the value 28.
The if
statement begins the conditional and checks whether the temperature is less than 20. If so, the code within the brackets { }
is executed and will print the sentence “It’s quite cold. Dress warmly!”
The else if
statement continues the conditional and checks whether the temperature is greater than 30. If that’s the case, the enclosed code will run, printing “It’s hot outside! Stay hydrated!”
The else
part, always at the end, doesn’t have a condition. It offers a default action when none of the previous conditions met. In other words, if the temperature is neither less than 20 nor more than 30, the code within these brackets will run, printing “The weather seems to be mild.”
Remember that the code follows the conditions in the order they are written, and firstly it does match, it executes. Thus, the values and conditions should be organized optimally to ensure accurate results. This structured approach to decision making allows programs to be more dynamic and respond differently based on various inputs or situations.