Created
July 26, 2022 22:33
-
-
Save IanKeen/aa7234291c81f9c4a06848fa1ba07bed to your computer and use it in GitHub Desktop.
SwiftUI: @StateObject.init(wrappedValue:) gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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