Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save couchdeveloper/ebaff1befa9ad2b0210366c4889393b1 to your computer and use it in GitHub Desktop.
Save couchdeveloper/ebaff1befa9ad2b0210366c4889393b1 to your computer and use it in GitHub Desktop.
import SwiftUI
// Demonstrates issue when assigning `@State` values in the initialiser
struct ContentView: View {
@State var string: String = "Initial" // default initialise the value
init(string: String) {
self.string = string // assign it again with value `string`
// We expect that `self.string` has been assigned the value `string`.
// However, due to how SwiftUI manages the state store, this is not always the case!
print("init: \(string), self.string: \(self.string)")
}
var body: some View {
return Text(string)
}
}
import PlaygroundSupport
// We expect that the view renders "Hello World!", but it renders "Initial"
PlaygroundPage.current.setLiveView(ContentView(string: "Hello World!"))
@couchdeveloper
Copy link
Author

Screenshot 2021-07-24 at 17 19 37

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