Learn iOS Development

Decision Making With Switch & If Expressions in Swift

Making Decisions in Style

Shashank Thakur
Mobile App Development Publication

--

Decision Making With Switch & If Expressions in Swift
Photo by JESHOOTS.COM on Unsplash

In the world of programming, making decisions is a fundamental task. Conditional statements allow your code to take different paths depending on specific conditions. In Swift, two powerful tools for making decisions are the if statement and the switch statement. In this blog, we will explore both if and switch expressions in Swift, showcasing their usage, features, and how they can help you write clean and efficient code.

The if Statement

The if statement is the most basic form of decision-making in Swift. It allows you to execute a block of code if a certain condition evaluates to true. Additionally, you can use else and else if clauses to handle alternative cases.

Basic if Statement

let temperature = 25

if temperature > 30 {
print("It's hot outside.")
} else {
print("It's not too hot.")
}

In this example, if the temperature is greater than 30, the first block of code will execute. Otherwise, the code inside the else block will run.

else if Clause

You can use else if to handle multiple conditions in a sequential manner:

let grade = 85

if grade >= 90 {
print("A")
} else if grade >= 80 {
print("B")
} else if grade >= 70 {
print("C")
} else {
print("F")
}

This code snippet assigns a grade based on the value of the grade variable.

Ternary Conditional Operator

Swift also supports a concise way of writing if-else expressions using the ternary conditional operator (? :):

let isRaining = true
let weatherMessage = isRaining ? "Bring an umbrella" : "Enjoy the sunshine"
print(weatherMessage)

This code assigns a message to weatherMessage based on the isRaining condition.

The switch Statement

The switch statement in Swift is a versatile tool for handling complex decision-making scenarios. It allows you to test a value against multiple possible cases and execute code based on the matching case.

Basic switch Statement

let dayOfWeek = "Wednesday"

switch dayOfWeek {
case "Monday":
print("It's the start of the week.")
case "Wednesday":
print("It's hump day!")
default:
print("It's just another day.")
}

Here, the code checks the value of dayOfWeek and prints a message accordingly. The default case handles any unhandled values.

Matching Ranges

switch statements in Swift can also match ranges of values:

let score = 75

switch score {
case 0..<50:
print("Fail")
case 50..<70:
print("Pass")
case 70...100:
print("Excellent!")
default:
print("Invalid score")
}

This code assigns a grade based on the score value using ranges.

Compound Cases

Swift allows you to combine cases to execute the same code for multiple cases:

let fruit = "apple"

switch fruit {
case "apple", "pear", "banana":
print("It's a fruit.")
default:
print("It's not a recognized fruit.")
}

In this example, if fruit matches any of the listed cases, it will execute the code inside the compound case.

Value Binding

You can also use value binding in switch statements to capture associated values:

let person = ("Alice", 30)

switch person {
case let (name, age) where age < 18:
print("\(name) is a minor.")
case let (name, age) where age >= 18:
print("\(name) is an adult.")
default:
print("Invalid data.")
}

This code captures the name and age values from the person tuple and uses them in the switch cases.

Conclusion

Conditional statements, including the if and switch statements are essential tools for controlling the flow of your Swift code. Depending on your needs, you can choose between the simplicity of if statements or the versatility of switch statements. Swift's rich syntax and expressive power make it a pleasure to work with, allowing you to write code that is not only functional but also elegant and easy to read. So, next time you need to make a decision in your Swift code, reach for these tools to make your code more organized and efficient.

--

--