Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. couchdeveloper created this gist Jul 24, 2021.
    23 changes: 23 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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!"))