How to use switch statements to check multiple conditions – Swift for Complete Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] you can use if and elseif to repeatedly check conditions as much as you want to but it can get awfully hard to read sometimes for example if we had a weather forecast like this one here as an enum weather case sun rain wind snow and unknown plus a constant called forecast equal the weather dot sun we could check those values using if else if again again and again to check them all and print out various appropriate messages using code like this we could say if it's sunny forecast print it should be a nice day if it's rainy pack an umbrella if it's windy wear something warm if it's rainy school is cancelled otherwise print out our forecast generator is broken and that code works that's valid swift but it has multiple problems first up we keep having to repeat ourselves forecast forecast forecast forecast we're checking the same thing again again and again but writing out repeatedly is quite tiresome second i've accidentally checked rain twice i've got rain packing umbrella and rain school is cancelled that was a mistake i didn't mean to check rain the second time around in fact i meant to check snow snow is currently not being checked so we're missing functionality schools being cancelled by accident right it shouldn't happen now we can solve all three of these problems using a different way of checking conditions called switch this also allows us to check individual cases sun rain wind rain unknown but now swift the compiler the program building our code is able to help us out do extra work on our behalf because it knows all the possible cases of our enum sun rain wind rain unknown so if you check one twice it'll complain if you forget to check one it will refuse to build your code and so we can replace all the if and else if and else all that junk and go away and replace with this code here a switch block let's break it down we start with switch forecast we're telling swift that's the value forecast that we want to check we then have a whole range of case checks is it sunny rainy windy snowy or unknown we're comparing that against forecast is forecast sunny it's forecast rainy windy snowy unknown it checks the valley at the top against each case down the line each of our cases lists exactly one weather type and because we're switching on forecast we haven't got a right weather.sun weather.rain weather.wind swift knows forecast is a kind of weather that is type and therefore all the cases are the same type after each case there's a colon to mark start the code that should be run when that is true so if it's sunny print it should be a nice day if it's rainy print pack an umbrella and then at the end you'll see a little closing brace to end the switch statement and we go on to the normal code afterwards now if you're trying an x code go ahead and change snow to rain like i had an if and else if option you'll see swift complains loudly it'll say you've checked rain twice and snow isn't checked swift will actually enforce that our switch blocks are exhaustive they cover all possible cases of the values always they're required in swift now if you've used other languages to program before you might realize that swift switches are a little bit different in two key places first up all switch in swift must be exhaustive you must check all possible values as you can't leave one off by accident it's not allowed not as enums but also strings integers anything you must always have a case for every possible result but second up and this catches people out of the coming from say c plus plus um what will happen with swift is it'll save forecast and it'll compare against the very first case or the second case third case it'll do them in order as soon as it finds one that matches which in our case will be the sun case it will run that code print it should be a nice day but in many older languages they'll run the first one and then carry on running the second one and the third and the fourth and the fifth and so forth they'll just carry on and they'll keep on doing that until they reach the end of the block and swift does not do that swift will only do the bit that actually matches and yes this is a huge difference but it makes so much more sense to do it this way quite frankly now both those two changes that are absolutely true swift does give us uh more control if we needed first yes all your switches have to be exhaustive you must ensure every possible case you're switching on is covered now if you're switching on a string clearly it is not feasible it's just impossible quite frankly to check every possible string ever case a case a a case a case a b you wouldn't do it it's impossible there is an infinite number of strings out there right so instead of having every possible string being checked we can provide a default case to run if none of the other cases match so let's try this in a playground over here i'll say we have let place equals metropolis and we're going to switch on this place string so i'll say switch place case gotham we will do print your batman then case mega city 1 print your judge dread and we'll do another case let's do wakanda i'll do print your black panther and then for all other strings we haven't handled explicitly a default case print who are you like that and this default case is it we don't say case default just default by itself it'll run if all other cases have failed to match and remember swift runs these checks in order it'll check gotham first then mega city one then wakanda and then finally for metropolis it'll get to default and print who are you if you place default higher up before any other case it will always be run before that case it'll basically make the rest of the code useless so i put default very top none of these cases here will ever be checked they cannot be checked because default will always run before them in fact swift even issued an error you can't have case blocks after default it's pointless it will never be run because the fault will come first so that is the first useful thing you can have default to have default action if none of the other cases match second if you explicitly want swift to carry on executing cases after the first one's matched you can do that by saying fall through fall through this is honestly not commonly used but sometimes just like one in a million times it will help you avoid repeating work for example there's a famous christmas song called the 12 days of christmas and as the song goes on more and more gifts are heaped on to some poor unfortunate person who has a massively full house by about day six and we can make a simple approximation of the song using four through first uh let's have a look how how a song might look without fall through so i'll say let day equals five and then we'll say print my true love gave to me and then switch on day if we are day five i'll print five golden rings if we're day four i'll print four calling birds if we are scroll down uh three our print three french hens two was two uh turtle doves and then at the very end of the song uh the default case is print a partridge in a pear tree and the way the song works is on day one you get a patch in a pear direct tree on day two you get two turtle doves and the partridge in a pear tree in day three you get three french hens two turtle doves and a party in a pear tree get longer and longer and longer until you're out of breath at the very end which is of course hilarious well it's supposed to be when you haven't got netflix anyway um if i run this code back now you're gonna see it's gonna print out five golden rings that's not we meant that's not quite right we want five golden rings four calling birds three french hens two little gloves and a partridge in a pear tree tree and that's where four through comes in i can add fall through here and here and here and here what it means is when day is five it will run case five print this and then fall through to case four it'll print four coiling birds then four through to case three print three french hens full through case two two doves full through to default case it'll work its way down let's print the code now we should see all these things being printed out boom it's not exactly the lyrics of the song but you get the idea so it'll match the first one print the line fall through again and again again but hopefully now you can at least see the functionality or fall through in action you
Info
Channel: Paul Hudson
Views: 8,193
Rating: undefined out of 5
Keywords:
Id: cDpJy4Y7OYE
Channel Id: undefined
Length: 10min 34sec (634 seconds)
Published: Mon Oct 04 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.