Conditionals & Logic
Learn how to develop complex programs in Swift with conditionals and logical operators.
StartKey Concepts
Review core concepts you need to learn to master this subject
if
Statement
else
Statement
else if
Statement
Comparison Operators
Ternary Conditional Operator
switch
Statement
switch
Statement: Interval Matching
switch
Statement: Compound Cases
if
Statement
if
Statement
var halloween = true
if halloween {
print("Trick or treat!")
}
// Prints: Trick or treat!
An if
statement executes a code block when its condition evaluates to true
. If the condition is false
, the code block does not execute.
Conditionals
Lesson 1 of 2
- 1On a daily basis, we’re faced with making decisions based on certain conditions; if the weather is beautiful, we’ll go for a walk, or if it’s rainy, we’ll stay in and code! In Swift, the ability …
- 2The if statement is the most basic and fundamental type of conditional in Swift. It is used to execute some code when a given condition is true. The structure of an if statement is: if condition…
- 3A tool most commonly used together with an if statement is the else statement. An else statement is used to execute a block of code when the condition of an if statement is false. Think of the el…
- 4So far, our conditions have consisted of a single variable whose value is a Boolean, true or false. With the help of operators, we can expand on this and create conditions that utilize multiple val…
- 5Until now, we’ve been working with conditionals that can handle only one condition. If that condition is met, our program follows one course of action, otherwise it follows another. Swift provide…
- 6A standard if/else statement can get pretty lengthy - at least 5 lines of code. Many developers prefer to keep their code as concise as possible and favor a shorter syntax. Swift allows us to minim…
- 7Another type of conditional statement that exists in Swift is the switch statement. The switch statement is a popular programming tool used to check the value of a given expression against multip…
- 8One super power that the switch statement possesses, is its ability to match values to an expression that exist within intervals. An interval denotes a range used for checking whether a given val…
- 9Another noteworthy ability of the switch statement is its use of multiple values in a single case. These are known as compound cases. The switch statement will match each value within a compound …
- 10Another neat feature available for the cases of a switch statement is the where clause. The where clause allows for additional pattern matching for a given expression. It can also be used with lo…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory