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 trialFrances Angulo
5,311 PointsElse If vs. Just plain old If
Why does the teacher use else if when if seemed to work okay?
Teacher's example:
for card in cards {
if card == 11 {
println("Jack")
}else if card == 12 {
println("Queen")
} else {
println(card)
}
}
My example seemed to return the same results:
for card in cards {
if card == 11 {
println("Jack")
}; if card == 12 {
println("Queen")
} else {
println(card)
}
}
3 Answers
Fahad Alrahbi
1,080 PointsHello , your question is for programming concept as well ,
if you write
if card == 11 {
println("Jack")
}else if card == 12 {
println("Queen")
} else {
println(card)
}
tha's mean if the first condition is true , compiler will skip other conditions as well , if the first condition is false the compiler will go to first else and will check if true so will skip other else as well ,
in other hand if you write
if card == 11 {
println("Jack")
};
if card == 12 {
println("Queen")
} else {
println(card)
}
thats mean the compiler will check the first condition and at same time will check the if card ==12 because they are in different scope or block .
finally if you have different case and you want if one of different is true you use if else , otherwise you can use single if .
Fahad Alrahbi
1,080 Pointsit should be there is some different and you will notice this different in case
This is my example
var x = 10
if(x==10){
// Display 10
let x=12
}else if (x==12){
// display 12
}
if (x==10){
//display 10
let x=12
}
if(x==12){
//display 12
}
i think now it's clear , in first example if will only display 10 , because the first condition is true , and it will skip the other if ,
in other ,
it will display 10 and 12
Note , I'm not writing by using any programming language , so you can convert my code to any language and check .
hope that was clear .
Samuel Seidel
1,481 PointsIt's basically just saving processing time.
Frances Angulo
5,311 PointsFrances Angulo
5,311 PointsBut the Assistant editor returned the same results - should it not have?