UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Switch statement

Forums > 100 Days of Swift

switch weather {
case "rain":
    print("Bring an umbrella")
case "snow":
    print("Wrap up warm")
case "sunny":
    print("Wear sunscreen")
    fallthrough
default:
    print("Enjoy your day!")
}

In this example, I understand the fallthrough will print the current case, but will the fallthrough go to the NEXT case or does it go to the default case?

3      

Assuming weather is sunny, the next case is the Default case, and fallthrough will go to the default case.

If the fallthrough was on an earlier case, it would go to the next case (not default), until a match is found. If none are found, then it would execute the default case.

3      

Okay so fallthrough doesn't go straight to default, it will keep iterating through the stack checking each case before reaching default. Okay, that's what I was wondering. Thanks.

3      

Okay so fallthrough doesn't go straight to default, it will keep iterating through the stack checking each case before reaching default.

No, fallthrough lets the code drop through to the very next case and then it stops there (unless, of course, there is also a fallthrough in that case too!). It doesn't do any more pattern matching at all.

So if you put a fallthrough in the "rain" case of your example switch statement, you will see the output:

Bring an umbrella
Wrap up warm

It won't keep going after that and won't ever reach default.

3      

@PhilHansonGH, I stand corrected.

I suggest that you mark @roosterboy's answer as the correct solution.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.