Skip to content

Instantly share code, notes, and snippets.

@schwa
Created March 27, 2021 15:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schwa/4ff3934539a1fe815b60c6a60f772322 to your computer and use it in GitHub Desktop.
Save schwa/4ff3934539a1fe815b60c6a60f772322 to your computer and use it in GitHub Desktop.
Dash Snippet for SwiftUI Environments & Modifiers
struct __ValueType__ {
}
struct __ValueType__Key: EnvironmentKey {
static var defaultValue = __ValueType__()
}
extension EnvironmentValues {
var __KeyName__: __ValueType__ {
get {
self[__ValueType__Key.self]
}
set {
self[__ValueType__Key.self] = newValue
}
}
}
struct __ValueType__Modifier: ViewModifier {
let value: __ValueType__
func body(content: Content) -> some View {
content.environment(\.__KeyName__, value)
}
}
extension View {
func __KeyName__(value: __ValueType__) -> some View {
self.modifier(__ValueType__Modifier(value: value))
}
}
@schwa
Copy link
Author

schwa commented Mar 27, 2021

And if you prefer Xcode style snippets:

struct <#ValueType#> {
}

struct <#ValueType#>Key: EnvironmentKey {
    static var defaultValue = <#ValueType#>()
}

extension EnvironmentValues {
    var <#KeyName#>: <#ValueType#> {
        get {
            self[<#ValueType#>Key.self]
        }
        set {
            self[<#ValueType#>Key.self] = newValue
        }
    }
}

struct <#ValueType#>Modifier: ViewModifier {
    let value: <#ValueType#>
    func body(content: Content) -> some View {
        content.environment(\.<#KeyName#>, value)
    }
}

extension View {
    func <#KeyName#>(value: <#ValueType#>) -> some View {
        self.modifier(<#ValueType#>Modifier(value: value))
    }
}

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