Switch Statement - Clarification

Hi There,

While learning about control-flow and switch statements, something came into my mind:

Inside the switch statement, we’re creating a new constant to access the name value inside our tuple, but instead of closing the parenthesis we’re adding a ( , ) and writing a range (0…2)

My question would be : are we creating a constant with a value of the range, or it’s simply there for some reason. Would love some clarification.

Greatly Appreciated in Advance :smile:

let person = (name: “Shay”, age: 20)
switch person {
case let (name, 0…2):
print(“(name) is an Infant”)

The elements inside the case statement’s tuple set up conditional matching for the parameters in the person tuple being used for the switch. It is a compact way of saying this case will be selected for any name if the age is within the range.

Hi Brian,

Thanks a lot for your answer!

I was wondering if you could explain what is conditional matching in relation to my code,
since I’m new to programming and don’t understand everything yet.

Hope you understand

Greatly Appreciated, Shay :smile:

The purpose of that piece of code is to determine how you want to categorize someone based upon their age; are they an infant, child, teenager, adult? Without a switch statement you would have to write a series of if-then-else-if statements, one for each category, to test a person’s age to determine the proper category for them. The switch statement is a simpler form of the if-then-else-if structure.

Older languages only allowed you to switch only on a single value. With Swift you can pass a tuple to the switch statement and with conditional matching you can test each element of the tuple for whatever conditions you require. In this case, there is no testing for the person’s name, just their age.

2 Likes

Thanks a lot Brian

Greatly Appreciated

This topic was automatically closed after 166 days. New replies are no longer allowed.