Browse Questions
  • FlowLayout uses the Layout protocol (iOS 16+) — SwiftUI's official first-party layout system.
  • 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.
  • setNeedsLayout schedules a layout pass for later, layoutIfNeeded forces any pending layout to happen immediately, and setNeedsDisplay schedules a redraw of the view's content.
  • Both inject values from the environment, but they serve different purposes.

Answer: Both inject values from the environment, but they serve different purposes.

  • @Environment — reads system or built-in values (color scheme, locale, font, dismiss action)
  • @EnvironmentObject — reads a custom ObservableObject injected by a parent view

Code Example:

// @Environment — built-in system values
struct ThemeAwareView: View {
    @Environment(\.colorScheme) var colorScheme
    @Environment(\.dismiss) var dismiss

    var body: some View {
        Text(colorScheme == .dark ? "Dark mode" : "Light mode")
        Button("Close") { dismiss() }
    }
}

// @EnvironmentObject — custom shared object
class AppSettings: ObservableObject {
    @Published var fontSize: CGFloat = 16
}

struct ChildView: View {
    @EnvironmentObject var settings: AppSettings

    var body: some View {
        Text("Hello").font(.system(size: settings.fontSize))
    }
}

// Must be injected by a parent
ContentView()
    .environmentObject(AppSettings())