0
0
Swiftprogramming~15 mins

Iterating enum cases with CaseIterable in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterating enum cases with CaseIterable
📖 Scenario: You are creating a simple app that shows different fruit options to users. You want to list all the fruits you support in your app.
🎯 Goal: Build a Swift program that defines an enum of fruits and uses CaseIterable to list all fruit cases.
📋 What You'll Learn
Create an enum called Fruit with cases apple, banana, and cherry
Make the Fruit enum conform to CaseIterable
Create a variable called allFruits that holds all cases of Fruit
Use a for loop with variable fruit to iterate over allFruits
Print each fruit case inside the loop
💡 Why This Matters
🌍 Real World
Enums with CaseIterable are useful when you want to list all options of a category, like fruit types, app themes, or user roles.
💼 Career
Understanding how to iterate enum cases helps in building clean, maintainable code for apps that need to handle fixed sets of options.
Progress0 / 4 steps
1
Create the Fruit enum with cases
Create an enum called Fruit with cases apple, banana, and cherry.
Swift
Need a hint?

Use enum Fruit { case apple, banana, cherry } or write each case on its own line.

2
Make Fruit conform to CaseIterable
Make the Fruit enum conform to CaseIterable by adding it after the enum name.
Swift
Need a hint?

Add : CaseIterable right after Fruit in the enum declaration.

3
Create allFruits variable with all cases
Create a variable called allFruits and set it to Fruit.allCases to get all enum cases.
Swift
Need a hint?

Use var allFruits = Fruit.allCases to get all cases.

4
Print all fruit cases using a for loop
Use a for loop with variable fruit to iterate over allFruits and print each fruit.
Swift
Need a hint?

Use print(fruit) inside the loop to show each fruit.