0
0
Swiftprogramming~30 mins

Enum methods and computed properties in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Enum methods and computed properties
📖 Scenario: You are creating a simple app that shows different types of fruits and their colors.
🎯 Goal: Build a Swift enum called Fruit with a method and a computed property to get the fruit's color and description.
📋 What You'll Learn
Create an enum called Fruit with cases apple, banana, and cherry
Add a computed property called color that returns the color of each fruit as a String
Add a method called description() that returns a sentence describing the fruit and its color
Print the description of each fruit
💡 Why This Matters
🌍 Real World
Enums with methods and computed properties help organize related data and behavior, like representing fruit types and their details in an app.
💼 Career
Understanding enums with methods and computed properties is important for writing clean, maintainable Swift code in iOS app development.
Progress0 / 4 steps
1
Create the Fruit enum
Create an enum called Fruit with cases apple, banana, and cherry.
Swift
Need a hint?

Use the enum keyword to define Fruit and list the cases inside curly braces.

2
Add a computed property for color
Add a computed property called color inside the Fruit enum that returns a String with the color for each fruit: "Red" for apple, "Yellow" for banana, and "Red" for cherry.
Swift
Need a hint?

Use a var with a switch on self to return the correct color.

3
Add a method to describe the fruit
Add a method called description() inside the Fruit enum that returns a String describing the fruit and its color, like "An apple is Red." Use the color computed property inside this method.
Swift
Need a hint?

Define a function that returns a string using self and the color property with string interpolation.

4
Print descriptions of all fruits
Create constants apple, banana, and cherry of type Fruit. Then print the result of calling description() on each constant.
Swift
Need a hint?

Create constants for each fruit case and print their descriptions using the description() method.