Nested Enums
Welcome to Lesson 3 of Advanced Enum. You will learn how to add multiple enums within an enum to design organized structure and design. This lesson will take your game to the next level.
Problem
Just more than one
Intro to Nested Enums
Create an enum called FutureCourse. It contains other enums called, LearnSwiftWithBob and UIKitFundamentals.
1. enum FutureCourse {
2. enum LearnSwiftWithBob: String {
3. case genericProtocol
4. case advancedEnum
6. var chapaterDescription: String {
7. return self.rawValue
8. }
9. }
11. enum UIKitFundamentals: String {
12. case realmDatabase
13. case noStoryboard
14. case cloudComputing
16. var chapterDescription: String {
17. return self.rawValue
18. }
19. }
21. }
23. Initialize an object
24. ```swift
25. FutureCourse.LearnSwiftWithBob.advancedEnum.chapaterDescription
26. FutureCourse.UIKitFundamentals.cloudComputing.chapterDescription
Game Design
Create a struct called, Character. Add a nested enum called CharacterType and Skill. The Character struct has two property whose types are CharacterType and Skill.
1. struct Character {
2. enum CharacterType {
3. case prince
4. case warrior
5. case priest
6. }
8. enum Skill {
9. case airwalk
10. case transparency
11. case prediction
12. }
14. let type: CharacterType
15. let skill: Skill
16. }
To initialize, you all have to pick and choose.
1. let warrior = Character(type: .priest, skill: .airwalk)
Important: Follow this pattern for designing your app.
Another Game Design
Instead of using a struct as above, you may achieve the similar outcome using enums only.
1. enum Wearable {
2. enum Weight: Int {
3. case light
4. case medium
5. case heavy
6. }
7. enum Price: Int {
8. case leather
9. case iron
10. case steel
11. }
13. case armor(weight: Weight, price: Price)
14. // case houseMaterial(weight: Weight, price: Price)
16. func getDescription() -> String {
17. switch self {
18. case let .armor(weight, price) :
19. return "You've chosen \(weight) and \(price)"
20. }
21. }
22. }
1. let myClothes = Wearable.armor(weight: .heavy, price: .steel)
2. myClothes.getDescription()
3. // "You've chosen heavy and steel"
You don’t have to create structs/classes for every design.
Source Code
Conclusion
You’ve learned how nested enums may be useful for replacing classic structs and classes. I recommend you use both of them. When you design APIs for your teammates or open source libraries, attempt to use enums for anything has to do with choosing options because the user of your code doesn’t’ have to type or go through multiple properties and methods all mixed together. Instead, enums allows him/her to pick and choose available cases for the particular enum. The skill that requires you to code in a different league is deploying enums in the right context.
In the following lesson, you will learn how to combine enums with protocols.
Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.
