0
0
Swiftprogramming~15 mins

Raw values for enums in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Raw values for enums
📖 Scenario: Imagine you are creating a simple app that needs to represent different types of fruits with specific codes. You want to use Swift enums with raw values to assign each fruit a unique code.
🎯 Goal: Build a Swift program that defines an enum with raw values for fruits and prints the raw value of a selected fruit.
📋 What You'll Learn
Create an enum called Fruit with raw values of type String
Include these fruits with exact raw values: apple = "A01", banana = "B02", cherry = "C03"
Create a variable called selectedFruit and assign it the enum case .banana
Print the raw value of selectedFruit using print
💡 Why This Matters
🌍 Real World
Enums with raw values are useful for representing fixed sets of related values with associated codes, like product categories, error codes, or status flags.
💼 Career
Understanding enums with raw values is important for Swift developers working on iOS apps, as it helps organize data clearly and safely.
Progress0 / 4 steps
1
Create the Fruit enum with raw values
Create an enum called Fruit with raw values of type String. Add these cases with exact raw values: apple = "A01", banana = "B02", cherry = "C03".
Swift
Need a hint?

Use enum Fruit: String and assign raw values with =.

2
Create a variable for the selected fruit
Create a variable called selectedFruit and assign it the enum case .banana from the Fruit enum.
Swift
Need a hint?

Use var selectedFruit = Fruit.banana to assign the enum case.

3
Access the raw value of the selected fruit
Create a constant called fruitCode and assign it the raw value of selectedFruit using the rawValue property.
Swift
Need a hint?

Use let fruitCode = selectedFruit.rawValue to get the raw value string.

4
Print the raw value of the selected fruit
Use print to display the value of fruitCode.
Swift
Need a hint?

Use print(fruitCode) to show the raw value.