songmoro 2024. 1. 10. 01:19
728x90

프로젝트 규모가 크지 않아 굳이 디자인 패턴을 적용하지 않아도 되긴 하지만, 유지보수의 용이를 위해 MVVM을 채택했습니다.

기존 코드들은 필요에 따라 해당 파일 내에 작성했었는데 Model, View, View Model 용도에 맞춰 코드를 옮겼습니다.

 

 

<Model>

enum Campus: String, CaseIterable {
    case 부산, 밀양, 양산
    
    var restaurant: [Restaurant] {
        switch self {
        case .부산:
            [Restaurant.금정회관학생, Restaurant.금정회관교직원, Restaurant.샛벌회관, Restaurant.학생회관학생, Restaurant.진리관, Restaurant.웅비관, Restaurant.자유관]
        case .밀양:
            [Restaurant.학생회관학생, Restaurant.학생회관교직원, Restaurant.비마관]
        case .양산:
            [Restaurant.편의동, Restaurant.행림관]
        }
    }
}

enum Week: String, CaseIterable {
    case 일, 월, 화, 수, 목, 금, 토
}

enum Category: String, CaseIterable, Hashable {
    case 조식, 중식, 석식
}

enum Restaurant: String, CaseIterable, Hashable {
    case 금정회관학생 = "금정회관 학생"
    case 금정회관교직원 = "금정회관 교직원"
    case 샛벌회관
    case 학생회관학생 = "학생회관 학생"
    case 진리관
    case 웅비관
    case 자유관
    // 학생회관 학생
    case 학생회관교직원 = "학생회관 교직원"
    case 비마관
    case 편의동
    case 행림관
}

struct Meal: Hashable {
    var foodByCategory: [Category: String] = [:]
}

struct QueryDatabase: Codable {
    var results: [QueryProperties]
    
    struct QueryProperties: Codable {
        var properties: [String: QueryProperty]

        struct QueryProperty: Codable {
            var type: String
            var rich_text: [RichText]?
            var select: [String: String]?
            
            struct RichText: Codable {
                var plain_text: String
            }
        }
    }
}

통신, 뷰, 데이터 등 모델입니다.

 

 

<View>

struct MainView: View {
    @Namespace private var namespcae
    @StateObject private var vm = MainViewModel()
    
    var body: some View {
		// ...
		}
}

뷰에 있던 State 변수, 함수들을 뷰 모델로 옮기고, vm 변수를 통해 관리합니다.

 

 

<View Model>

class MainViewModel: ObservableObject {
    @Published var menu: [Week: [Restaurant: Meal]] = [:]
    @Published var selectedCampus = "부산"
    @Published var selectedDay = ""
    @Published var isSheetShow = false
    @Published var weekday: [Week: Int] = [:]
    
    func currentWeek() {
        // ...
    }
    
    func requestCampusDatabase() {
        // ...
    }
}

뷰 모델로 옮긴 함수의 변수를 제거하고, 뷰 모델 내부에서 관리하도록 합니다.

728x90