Swift's switch is the only one that I think gets it right. It provides enough simplicity and usability to warrant use over if-else chains.
switch
From docs.swift.org/swift-book/Language...
case "a", "A":
case 1..<5:
switch point: case (0, 0)
case let(x, y)
where
fallthrough
Granted, each of these can still be done with if-else, I like the convenience of it all.
This here. switch in some languages (like F#, rust, and apparently swift- amongst others) has additional "powers".
In C# 8 you can also use it as an expression:
return x switch { 0: something, // More _: whatever, };
Otherwise it's main advantage is clarity for large numbers of options and optional fall through (double-edged sword that it is).
if (x == 0) { return something; } else if (x == 1) { // 10 more cases else { return whatever; } // vs switch (x) { case 0: return something; // 10 more default: return whatever; }
Regardless what you do with your brackets/whitespace, the switch logic is clearly only about the value of x.
x
Also, historically compilers were more likely to turn it into a jump table rather than chain of branches.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Swift's
switch
is the only one that I think gets it right. It provides enough simplicity and usability to warrant use over if-else chains.From docs.swift.org/swift-book/Language...
case "a", "A":
case 1..<5:
switch point: case (0, 0)
case let(x, y)
where
checksfallthrough
Granted, each of these can still be done with if-else, I like the convenience of it all.
This here.
switch
in some languages (like F#, rust, and apparently swift- amongst others) has additional "powers".In C# 8 you can also use it as an expression:
Otherwise it's main advantage is clarity for large numbers of options and optional fall through (double-edged sword that it is).
Regardless what you do with your brackets/whitespace, the switch logic is clearly only about the value of
x
.Also, historically compilers were more likely to turn it into a jump table rather than chain of branches.