0
0
Swiftprogramming~15 mins

Switch with compound cases in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Switch with compound cases
📖 Scenario: Imagine you are building a simple app that categorizes fruits based on their names. You want to group some fruits together because they share similar characteristics.
🎯 Goal: You will create a program that uses a switch statement with compound cases to print the category of a fruit.
📋 What You'll Learn
Create a variable called fruit with the value "apple".
Create a variable called citrusFruits that holds the fruits "orange" and "lemon".
Use a switch statement on the fruit variable with compound cases to check if the fruit is an apple or banana, or if it is a citrus fruit.
Print the category of the fruit using print.
💡 Why This Matters
🌍 Real World
Grouping items by categories is common in apps that organize data, like grocery lists or inventory systems.
💼 Career
Understanding switch statements with compound cases helps in writing clear and efficient code for decision-making in many software projects.
Progress0 / 4 steps
1
Create the fruit variable
Create a variable called fruit and set it to the string "apple".
Swift
Need a hint?

Use var fruit = "apple" to create the variable.

2
Create the citrusFruits array
Create a variable called citrusFruits and set it to an array containing the strings "orange" and "lemon".
Swift
Need a hint?

Use var citrusFruits = ["orange", "lemon"] to create the array.

3
Write the switch statement with compound cases
Write a switch statement on the variable fruit. Use compound cases to group "apple" and "banana" together, and use the citrusFruits array to group citrus fruits. For "apple" and "banana", print "Common fruit". For citrus fruits, print "Citrus fruit". For any other fruit, print "Other fruit".
Swift
Need a hint?

Use case "apple", "banana" for the first group and case let x where citrusFruits.contains(x) for citrus fruits.

4
Print the result
Run the program to print the category of the fruit stored in fruit.
Swift
Need a hint?

The output should be Common fruit because fruit is "apple".