The Swift language has a very interesting and intuitive way to work with switch-case breaks, with partial-matching, pattern-matching, etc. techniques, see these examples:
let age = 33
switch(age){
case let x where x >= 0 && x <= 2:
print("Infant")
case let x where x >= 3 && x <= 12:
print("Child")
case let x where x >= 13 && x <= 19:
print("Teenager")
case let x where x >= 20 && x <= 39:
print("Adult")
case let x where x >= 40 && x <= 60:
print("Middle aged")
case let x where x >= 61:
print("Elderly")
default:
print("Invalid")
}
Another very interesting example:
let string = "Dog"
switch(string){
case "Cat","Dog":
print("Domestic animal")
case "Lion","Leopard","Pantera":
print("Never touch me")
default:
print("By the way, don't touch... :-)")
}
Are there other languages that enable these features? I've never been able to make a switch case in Java. I've also never been curious to know if it would work :-) I've always used a different logic approach.
Editing: Adding an incredible example of "partial matching":
let coordinates: (x: Int, y: Int, z: Int) = (3, 0, 0)
switch (coordinates) {
case (0, 0, 0): // 1
print("Origin")
case (_, 0, 0): // 2
print("On the x-axis.")
case (0, _, 0): // 3
print("On the y-axis.")
case (0, 0, _): // 4
print("On the z-axis.")
default: // 5
print("Somewhere in space")
}
In the above case, the program will parse by default, since it is a point in X and the rest of the axes in zero. "On the X axis". In Java I would not use a switch case and simply a getX of the object not interested the rest, everything with else if, would write less and would have the same result. But I found it different how Swift had that freedom.
It seems to me that VB also has a similar technique.
Hugs to all.