Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Collections and Control Flow Control Flow With Conditional Statements If Statement

If Statements

As it was showed on the video, first we put the if statement, second else statement and then we put the else if between them. So, is it an order on if Statement?

Anatolii Tcai
Anatolii Tcai
2,401 Points

Right. The first one is always if. Then you can add as many else statements as you need. Moreover, it is possible to use only one statement without any else conditions. For example, I want to print a message when satisfying a condition, but if not - I don't need to write anything. In this case you can use only if:

var x = 25

if x > 0 { print("(x) is above 0") }

// Otherwise we just skip this part and continue our code

3 Answers

Yes, you always start with if, then you can put as many else if statements as you want or none at all and optionally end it with an else.

Quinton Gordon
Quinton Gordon
10,985 Points

Yep just remember that if you have more than one if statement "else" will always be your last statement. That's the standard / best practice. As the video actually showed even the "else" statement is optional. You can actually have an "if" with multiple "else if" and no "else" but doing so is not considered a good practice.

SivaKumar Kataru
SivaKumar Kataru
2,386 Points

If - else statements control the flow of the program. If you have one condition to check then if- else statement does it for you.

Lets say, if you have more than one condition to check then we can nest else-if statements followed by the IF. Also keep remember, Order has to be followed while using the else-if statements.

Example:

    let password  =  "1234"
    var maxLoginAttempts = 3
    if password == "1234" {
        print("Login Success");
    } else if password != "1234" {
       maxLoginAttempts -= 1
       print("Login Failed! No of attempts left: \(maxLoginAttempts)");
    } 

In the above example, we haven't used ELSE statement. Its completely optional depends on logic of your program. ```