Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Created April 18, 2025 06:40
Show Gist options
  • Save VAndrJ/67dcccc2b7dc4c4e4a2a9407edec7cbb to your computer and use it in GitHub Desktop.
Save VAndrJ/67dcccc2b7dc4c4e4a2a9407edec7cbb to your computer and use it in GitHub Desktop.
Environment values example.
//
// ContentView.swift
// EnvironmentExample
//
// Created by VAndrJ on 4/18/25.
//
import SwiftUI
enum Destination {
case openURL
case environment
}
struct ContentView: View {
var body: some View {
NavigationStack {
List {
NavigationLink("openURL example", value: Destination.openURL)
NavigationLink("EnvironmentValues example", value: Destination.environment)
}
.navigationDestination(for: Destination.self) { destination in
switch destination {
case .openURL: OpenURLExampleView()
case .environment: EnvironmentExampleView()
}
}
}
}
}
struct OpenURLExampleView: View {
@Environment(\.openURL) private var openURL
var body: some View {
let _ = Self._printChanges()
VStack {
Button("Open URL") {
openURL(.example)
}
SomeView()
}
}
}
struct EnvironmentExampleView: View {
@Environment(\.self) private var environment
var body: some View {
let _ = Self._printChanges()
VStack {
Button("Open URL") {
environment.openURL(.example)
}
SomeView()
}
}
}
struct SomeView: View {
init() {
print(#function, Self.self, UUID())
}
var body: some View {
Text("SomeView")
}
}
extension URL {
static let example = URL(string: "https://tinyurl.com/mpkrupzs")!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment