Ad space (banner)
๐ŸฆSwift Lessons
Lesson 4 / 68

Conditionals (if statements)

In this lesson you will learn how to write if statements in Swift so your program can branch based on a condition. This is for anyone searching for "Swift if statement syntax".

if / else if / else handles conditional branching, and the condition needs no parentheses around it. It helps to picture it as translating an everyday decision such as "if it is raining, take an umbrella" into code.

The sample code prints one of three messages depending on score using if / else if / else. Dropping the parentheses keeps the code noticeably tidier, which is characteristic of Swift.

A common stumbling block for beginners is trying to drop the braces {} as well. The parentheses are optional but the braces are mandatory, which can trip you up if you have experience in other languages.

In real-world development, comparisons use operators such as >, <, and ==, and stacking more else if clauses expresses three or more branches naturally, making the if statement a construct used in virtually every app.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)