Skip to content

Instantly share code, notes, and snippets.

@mdznr
Last active August 29, 2015 14:02
Show Gist options
  • Save mdznr/dbfa4bdfcb45f0f9dc3b to your computer and use it in GitHub Desktop.
Save mdznr/dbfa4bdfcb45f0f9dc3b to your computer and use it in GitHub Desktop.
The way switch statements work is different in Swift than in other languages, like C.
var total : Int
let myString = "foo"
// When originally looking at Swift's switch statements, you may think this is how you get fall through behaviour:
total = 0
switch myString {
case "foo":
total += 4
case "foo", "bar":
total += 2
default:
total += 1
}
total // 4
// But that didn't give you the expected value of 6 for `total`. So maybe you go and try this:
total = 0;
switch myString {
case "foo", "bar":
total += 2
case "foo":
total += 4
default:
total += 1
}
total // 2
// That still didn't work. Only the first match is executed. Here's where the `fallthrough` keyword comes in:
total = 0;
switch myString {
case "foo":
total += 4
fallthrough
case "bar":
total += 2
default:
total += 1
}
total // 6
// `fallthrough` is basically the opposite of `break` in C. Falling through is now opt-in instead of opt-out. This is one example of how Swift is more modern than C. In modern uses of switch statements, almost all of them want the break behaviour. Make this default and reduce code error.
@ArtSabintsev
Copy link

This is awesome, @mdznr! So they fundamentally changed how Switch works. In C languages, fallthrough was the default effect if we didn't add a break. In Swift, you have to specify fallthrough, to get the effect of sharing conditional changes in case statements. That's smarter in my opinion. Less of a chance to make a mistake!

@Blackjacx
Copy link

Wow thats great! Hated writing break under each case statement!
Nice :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment