Browse Questions
  • An Optional is a type that can hold either a value or nil.
  • Use protoc with the Swift plugin to generate Swift files from a .proto file provided by the backend team.
  • MVVM (Model-View-ViewModel) separates business logic from UI.
  • Encapsulation means bundling data with the operations that act on it, and restricting direct access to that data so internal invariants can't be broken from outside.

Answer: MVVM (Model-View-ViewModel) separates business logic from UI. The ViewModel exposes data and actions; the View observes and renders. No direct reference from ViewModel → View.

Model ←→ ViewModel ←→ View
           ↑
    (no UIKit/SwiftUI imports)

Code Example:

// Model
struct Article: Codable {
    let title: String
    let body: String
}

// ViewModel — no UIKit, no View references
@MainActor
class ArticleViewModel: ObservableObject {
    @Published var title: String = ""
    @Published var body: String = ""
    @Published var isLoading: Bool = false

    func load(id: String) async {
        isLoading = true
        let article = try? await ArticleService.fetch(id: id)
        title = article?.title ?? ""
        body = article?.body ?? ""
        isLoading = false
    }
}

// View — only rendering logic
struct ArticleView: View {
    @StateObject var viewModel = ArticleViewModel()

    var body: some View {
        VStack {
            if viewModel.isLoading {
                ProgressView()
            } else {
                Text(viewModel.title).font(.title)
                Text(viewModel.body)
            }
        }
        .task { await viewModel.load(id: "123") }
    }
}