Enumerations, Properties & Methods
Master iOS Enumerations with Properties and Methods
Key Concepts You'll Master
Enum Variables
Learn to add computed properties to enumerations for enhanced functionality. Properties can derive values from enum cases dynamically.
Enum Methods
Discover how to add mutating functions that can modify enum instances. Methods enable sophisticated state management within enums.
Type Association
Understand how to flip between different associated types and computed properties for flexible enum design patterns.
Setup Requirements
Launch Xcode
Open Xcode and create a new Playground file under iOS Blank template
File Organization
Navigate to Desktop > Class Files > yourname-iOS App Dev 1 Class directory
Save Project
Save the file as Enums-methods.playground and click Create to begin
When you print an enum directly, you see the case name. Use .rawValue to access the associated String or Int value assigned to each case.
DayOfTheWorkWeek Enum Structure
The workDayNumber variable is a computed property that doesn't store data but derives values from enum cases using switch statements.
Enum Cases vs Computed Properties
| Feature | Raw Value | Computed Property |
|---|---|---|
| Storage | Stores actual data | Calculates dynamically |
| Access Method | .rawValue | .workDayNumber |
| Memory Usage | Fixed allocation | No storage overhead |
| Flexibility | Static assignment | Dynamic calculation |
When enum methods need to modify the instance itself, you must use the mutating keyword. This allows the method to assign a new value to self.
Advance Function Logic
Switch on Self
The advance function uses a switch statement to evaluate the current enum value
Assign New Value
Each case assigns the next weekday to self, creating a cycling pattern
Handle Wrap-around
Friday advances back to Monday, completing the work week cycle
Int vs String Associated Types
When a computed property only has a getter and no setter, Swift automatically provides implicit getter behavior. You don't need to explicitly write the get keyword.
Key Takeaways