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

When to use If statement or Switch statement.

Hello I'm taking the Switch Basics course and was wondering, in which situations should i use a If statement and when should i use Switch statement. Why is one of them better in certain situations? Please explain.

hey there Mikkel, i think you mean the "switch" statement right? if thats the case then the thing with SWITCH statements is that they offer more feature than IF statements. they are in essence the same thing. but to use a SWITCH statement you have to use "case", also it lets you specify a range of possible "case" i think of it as this.

case = "in case this is TRUE" {preform this action}

also remember you need to have a default value in there. just in case its "FALSE" pretty much the same thing as ELSE.

import UIKit

let cards = 1...13

for card in cards { switch card { case 11: println ("Jack") case 12: println ("Queen") case 13: println ("King") default : println (card) }

//first off we begin by delcaring a CONSTANT named "cards" and assinging it a range of 1...13 //then we use our "For In" loop to iterate over that range of numbers. //we then implicitly declared another CONSTANT named "card" //the next step is to iterate everything inside the {} after "cards" //switch is the same as "IF" just with more feature // but you use "case" i think it stands for "in case" so by that mentality. it means "in case card is 11" then print out that its a jack //this gets repeated for the other two scenarios. and then lastly there is a "default" //the default means that in case none of those "case" come back TRUE then you would print the value of "card"

You i meant Switch ;) Just corrected it.. But i was more searching for at certain situations, where it would be better to use a Switch statement instead of a If statement. But thanks anyway ;-)

well it really depends on you and what your working on . switch statements let you use RANGES so like in the card example i put. you would want to use a SWITCH because you can print out a description if the card is between 11-13. so you can display "trump card" if it falls between those. you cant do that with IF statements. you would have to write an IF statement for each scenario.