본문 바로가기
iOS/Study

[Swift] Enum with Reusable VC

by Callie_ 2023. 10. 10.

⚙️ Setting

- iOS 16 ↑
- Swift vesrion 5.9
- Xcode version 15
 

🔖 Background Info

- During the development of my first app, Zickwan, I encountered a challenge: the UI design and features of the writing and editing view controllers were identical. Creating two separate view controllers wasn't ideal for efficient memory management.

 

 

✏️ Steps

- To achieve reusable views, enums proved to be a valuable tool. Here are the steps to make views reusable using enums.

 

 

1. Define TransitionType with an enum: Enum cases represent different roles when switching between views. In my case, I established roles for adding and editing.

 

enum TransitionType: String {
    case add
    case edit
}

 

 

2. Declare the type in the initial ViewController: The initial view controller, by default, will be for adding. This is achieved by declaring the type as .add.

 

var type : TransitionType = .add

 

 

3. Utilize a switch statement to separate functions: The switchingData() function uses the type enum to execute specific actions based on whether it's an add or edit scenario.

 

func switchingData() {
        
        switch type {
        case .add:
            
            print("add")
            
        case .edit:
            print("edit")
        }
        
    }

 

 

 

✅ Enum

- Enumerations (Enum)?

 

Enumerations (Enums) are a powerful feature in Swift, defining a type for a group of related values. They offer several benefits:

 

1. Compile-time Error Recognition:

Errors are identified at compile time, enhancing the robustness of the code.

 

2. Reduction of Human Errors:

Enums help minimize mistakes by providing a clear set of options.

 

3. Narrowing Down Value Selections:

By defining specific values, enums guide and limit the selection of options.

 

4. Forcing Selections Among Limited Values:

Enums encourage developers to choose from a predefined set of values, contributing to code consistency.

 

 

 

 

 

 


 

'iOS > Study' 카테고리의 다른 글

[iOS] Keychain vs UserDefaults  (0) 2023.12.17
[Study/iOS] Method Dispatch  (0) 2023.12.02
[iOS] 앱의 생명주기  (0) 2023.11.27
[Study/iOS] unowned vs weak  (2) 2023.11.14
[iOS] Shadow vs ClipsToBound  (0) 2023.07.23