Created
October 20, 2025 08:01
-
-
Save dterekhov/2febe3d74a9fa306bc655d202cda0d0f to your computer and use it in GitHub Desktop.
Safely access environment objects in SwiftUI #swiftui
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } |
Author
dterekhov
commented
Oct 20, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment