Introducing conditionals
At times, you’ll want to execute different code blocks based on a specific condition, such as in the following scenarios:
- Choosing between different room types at a hotel. The price for bigger rooms would be higher.
- Switching between different payment methods at an online store. Different payment methods would have different procedures.
- Deciding what to order at a fast-food restaurant. Preparation procedures for each food item would be different.
To do this, you would use conditionals. In Swift, this is implemented using the if
statement (for a single condition) and the switch
statement (for multiple conditions).
For more information on conditionals, visit https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow.
Let’s see how if
statements are used to execute different tasks depending on a condition’s value in the next section.