Skip to content

Instantly share code, notes, and snippets.

@hiimtmac
Created October 18, 2022 21:06
Show Gist options
  • Save hiimtmac/fd13c5fd381c28aadf352f43eb0167fa to your computer and use it in GitHub Desktop.
Save hiimtmac/fd13c5fd381c28aadf352f43eb0167fa to your computer and use it in GitHub Desktop.
Broken SwiftUI
import SwiftUI
protocol MyBrokenStyle {
associatedtype Body: View
func makeBody(configuration: MyBrokenStyleConfiguration) -> Body
}
struct MyBrokenStyleConfiguration {}
struct DefaultMyBroken: View {
let configuration: MyBrokenStyleConfiguration
var body: some View {
Text(":(")
}
}
struct DefaultMyBrokenStyle: MyBrokenStyle {
func makeBody(configuration: MyBrokenStyleConfiguration) -> some View {
DefaultMyBroken(configuration: configuration)
}
}
extension MyBrokenStyle where Self == DefaultMyBrokenStyle {
static var `default`: DefaultMyBrokenStyle { .init() }
}
struct MyBrokenStyleKey: EnvironmentKey {
static let defaultValue: any MyBrokenStyle = DefaultMyBrokenStyle()
}
extension EnvironmentValues {
var myBrokenStyle: any MyBrokenStyle {
get { self[MyBrokenStyleKey.self] }
set { self[MyBrokenStyleKey.self] = newValue }
}
}
extension View {
func myBrokenStyle(_ style: some MyBrokenStyle) -> some View {
environment(\.myBrokenStyle, style)
}
}
struct MyNotBroken1: View {
@Environment(\.myBrokenStyle) var style
var body: some View {
AnyView(style.makeBody(configuration: .init()))
}
}
struct MyNotBroken2: View {
@Environment(\.myBrokenStyle) var brokenStyle
var body: some View {
AnyView(brokenStyle.makeBody(configuration: .init()))
}
}
struct MyBroken: View {
@Environment(\.myBrokenStyle) var myBrokenStyle
var body: some View {
AnyView(myBrokenStyle.makeBody(configuration: .init()))
}
}
@hiimtmac
Copy link
Author

image

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