Skip to content

Instantly share code, notes, and snippets.

@christianselig
Last active March 28, 2024 19:00
Show Gist options
  • Save christianselig/4b835f6544ffe1c5c104ade74da8459e to your computer and use it in GitHub Desktop.
Save christianselig/4b835f6544ffe1c5c104ade74da8459e to your computer and use it in GitHub Desktop.
import SwiftUI
@Observable
class IceCreamParlor {
var iceCream: IceCream?
}
@Observable
class IceCream {
var flavor: String
init(flavor: String) {
self.flavor = flavor
}
}
struct ContentView: View {
@State var parlor: IceCreamParlor
var body: some View {
VStack {
Text("Welcome to the Ice Cream Parlor!")
if let iceCream = parlor.iceCream {
IceCreamMakerView(flavor: $iceCream.flavor)
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
parlor.iceCream = IceCream(flavor: "chocolate")
}
}
}
}
struct IceCreamMakerView: View {
@Binding var flavor: String
var body: some View {
Button {
flavor = ["chocolate", "vanilla", "strawberry"].randomElement()!
} label: {
Text("Random Ice Cream")
}
}
}
@aheze
Copy link

aheze commented Mar 28, 2024

Both should work!

import SwiftUI

@Observable
class IceCreamParlor {
    var iceCream: IceCream?
}

@Observable
class IceCream {
    var flavor: String

    init(flavor: String) {
        self.flavor = flavor
    }
}

struct ContentView: View {
    @State var parlor = IceCreamParlor()

    var body: some View {
        VStack {
            Text("Welcome to the Ice Cream Parlor!")

            if let iceCream = parlor.iceCream {
                // option 1!
                let binding = Binding {
                    iceCream
                } set: { newValue in
                    parlor.iceCream = newValue
                }
                IceCreamMakerView(flavor: binding.flavor)

                // option 2!
                @Bindable var bindable = iceCream
                IceCreamMakerView(flavor: $bindable.flavor)
            }
        }
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
                parlor.iceCream = IceCream(flavor: "chocolate")
            }
        }
    }
}

struct IceCreamMakerView: View {
    @Binding var flavor: String

    var body: some View {
        Button {
            flavor = ["chocolate", "vanilla", "strawberry"].randomElement()!
        } label: {
            Text("Random Ice Cream")
        }
    }
}

@christianselig
Copy link
Author

@aheze So simple in hindsight! Thank you!

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