Skip to content

Instantly share code, notes, and snippets.

@dterekhov
Created October 20, 2025 08:01
Show Gist options
  • Select an option

  • Save dterekhov/2febe3d74a9fa306bc655d202cda0d0f to your computer and use it in GitHub Desktop.

Select an option

Save dterekhov/2febe3d74a9fa306bc655d202cda0d0f to your computer and use it in GitHub Desktop.
Safely access environment objects in SwiftUI #swiftui
import SwiftUI
// MARK: - Safe environment access example
struct LibraryView: View {
// Retrieves a non-optional environment value; throws if not set
@Environment(Library.self) private var library
var body: some View {
// Your view content here
Text("Library loaded: \(library.name)")
}
}
// MARK: - Safe optional variant
struct SafeLibraryView: View {
// Retrieves an optional environment value; returns nil if missing
@Environment(Library.self) private var library: Library?
var body: some View {
if let library {
Text("Library: \(library.name)")
} else {
Text("Library unavailable")
.foregroundStyle(.secondary)
}
}
}
// Example model
struct Library {
let name: String
}
@dterekhov
Copy link
Author

3E708522-3982-486B-BCEC-06F0CF71F055

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment