In this tutorial, you’ll learn how to work with the Power Apps Switch function. This function is useful for evaluating a single formula against multiple possible values and executing corresponding actions.
Syntax Overview
The basic syntax of the Switch
function is:
Switch( Formula, Match1, Result1, Match2, Result2, ... )
It compares the result of the formula with each match value. If a match is found, the corresponding result is returned or executed.
Example: Displaying City Images
Let’s build a simple app that displays an image based on the selected city from a dropdown menu.
- Add a Dropdown control and set its
Items
property to:
[“Please select a city”, “New York City”, “Houston”, “Atlanta”, “San Diego”, “Miami”] - Add an Image control and set its
Image
property using theSwitch
function:
Switch( Dropdown1.Selected.Value,
“New York City”, “https://example.com/nyc.jpg”,
“Houston”, “https://example.com/houston.jpg”,
“Atlanta”, “https://example.com/atlanta.jpg”,
“San Diego”, “https://example.com/sandiego.jpg”,
“Miami”, “https://example.com/miami.jpg” )
Now, when a city is selected, the corresponding image will be displayed.
Conditional Logic with Nested Functions
You can nest other functions inside Switch
. For example, use a Radio control to toggle between day and night images for Miami:
- Add a Radio control with
Items
set to: [“Day”, “Night”] - Update the Miami case in the
Switch
function:
Switch( Dropdown1.Selected.Value,
“New York City”, “url/nyc.jpg”,
“Houston”, “url/houston.jpg”,
“Atlanta”, “url/atlanta.jpg”,
“San Diego”, “url/sandiego.jpg”,
“Miami”,
If(RadioTime.Selected.Value = “Day”, url/miami_day.jpg”, “url/miami_night.jpg”
)
)
This allows dynamic image switching based on both city and time of day.
Navigation Example
You can also use Switch
to navigate to different screens based on the selected city:
- Add a Button and set its
OnSelect
property:
Switch( Dropdown1.Selected.Value,
“New York City”, Navigate(NewYorkCityScreen),
“Houston”, Navigate(HoustonScreen),
“Atlanta”, Navigate(AtlantaScreen),
“San Diego”, Navigate(SanDiegoScreen),
“Miami”, Navigate(MiamiScreen) )
Clicking the button will take the user to the appropriate city screen.
When to Use Switch vs. If
- Use Switch when testing one variable against multiple known values.
- Use If when testing multiple variables or complex conditions.
Conclusion
The Switch
function is a powerful and cleaner alternative to multiple If
statements when dealing with a single variable and known values. It enhances readability and simplifies logic in Power Apps.
Leave a Comment