Title here
Summary here
Switch statements express conditionals across many branches.
Here’s a basic `Switch`.
```wolfram
i = 2;
Print["Write ", i, " as "];
Switch[i,
1, Print["one"],
2, Print["two"],
3, Print["three"]
]
You can use commas to separate multiple expressions in the same case
statement. We use the optional default
case in this example as well.
day = DateString[{"DayName"}];
Switch[day,
"Saturday" | "Sunday", Print["It's the weekend"],
_, Print["It's a weekday"]
]
Switch
without an expression is an alternate way to express if/else logic. Here we also show how the case
expressions can be non-constants.
t = Now;
Switch[True,
Hour[t] < 12, Print["It's before noon"],
_, Print["It's after noon"]
]
A type Switch
compares types instead of values. You can use this to discover the type of a value. In this example, we define a function whatAmI
that will print the type of its argument.
whatAmI[i_] := Switch[i,
_Integer, Print["I'm an int"],
_Real, Print["I'm a real number"],
_String, Print["I'm a string"],
_, Print["Don't know type ", Head[i]]
]
whatAmI[True]
whatAmI[1]
whatAmI["hey"]
The output of these examples will be:
Write 2 as two
It's a weekday
It's after noon
Don't know type True
I'm an int
I'm a string