konohazukux / swiftSample

0 stars 0 forks source link

mvvm #10

Closed konohazukux closed 4 months ago

konohazukux commented 4 months ago

MVVMパターンに基づいて、以下のようにコードを再構成しました:

ViewModel

//
//  ToDoViewModel.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import Foundation

class ToDoViewModel: ObservableObject {
  @Published var toDoItems = [
    ToDoItem(title: "Buy groceries", isCompleted: false),
    ToDoItem(title: "Walk the dog", isCompleted: true),
    ToDoItem(title: "Read a book", isCompleted: false)
  ]
}

View

//
//  ContentView.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import SwiftUI

struct ContentView: View {
  @StateObject private var viewModel = ToDoViewModel()

  var body: some View {
    NavigationView {
      List(viewModel.toDoItems) { item in
        HStack {
          Text(item.title)
          Spacer()
          if item.isCompleted {
            Image(systemName: "checkmark.circle.fill")
              .foregroundColor(.green)
          } else {
            Image(systemName: "circle")
              .foregroundColor(.gray)
          }
        }
      }
      .navigationTitle("To-Do List")
    }
  }
}

#Preview {
  ContentView()
}

Model

//
//  ToDoItem.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import Foundation

struct ToDoItem: Identifiable {
  let id = UUID()
  let title: String
  let isCompleted: Bool
}

App Entry

//
//  MyListAppApp.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import SwiftUI

@main
struct MyListAppApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

これで、MVVMパターンに従った構成となります。ViewModelがデータの管理を行い、Viewはそのデータを表示する役割を担っています。

konohazukux commented 4 months ago

8e4e2f614871134c75960dcd18974e44fce6b1f2