Last active
August 29, 2015 14:02
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow thats great! Hated writing break under each case statement!
Nice :)