Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created July 26, 2022 22:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/aa7234291c81f9c4a06848fa1ba07bed to your computer and use it in GitHub Desktop.
Save IanKeen/aa7234291c81f9c4a06848fa1ba07bed to your computer and use it in GitHub Desktop.
SwiftUI: @StateObject.init(wrappedValue:) gotcha
struct Parent: View {
@State private var foo = "foo" {
didSet { print("Parent", foo) }
}
var body: some View {
VStack {
Inner(value: foo)
Button("Parent Double") {
foo = [foo, foo].joined(separator: ":")
}
}
}
}
class VM: ObservableObject {
@Published var value: String = "" {
didSet { print("Inner", value) }
}
init(value: String) {
self.value = value
}
func double() {
value = [value, value].joined(separator: " ")
}
}
struct Inner: View {
@StateObject private var vm: VM
init(value: String) {
self._vm = .init(wrappedValue: .init(value: value))
}
var body: some View {
VStack {
Text("Value: \(vm.value)")
Button("Inner Double") { vm.double() }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment