title: How to associate a block of code with a @State var when it changes
body: <p>Whenever the value of the <code>@State</code> variable <code>myData</code> changes I would like to be notified and store that data in an <code>@AppStorage</code> variable <code>myStoredData</code>.  However, I don't want to have to write explicitly this storing code everywhere the state var is changed, I would like to associate a block of code with it that gets notified whenever the state var changes and performs storage.  The reason for this is, for example, I want to pass the state var as a binding to another view, and when that view would change the variable, the storage block would automatically be executed.  How can I do this/can I do this in SwiftUI?</p>
  <pre><code>struct MyView : View {
    @AppStorage(&quot;my-data&quot;) var myStoredData : Data!
    @State var myData : [String] = [&quot;hello&quot;,&quot;world&quot;]
    var body : some View {
      Button(action: {
        myData = [&quot;something&quot;,&quot;else&quot;]
        myStoredData = try? JSONEncoder().encode(myData)
      }) {
        Text(&quot;Store data when button pressed&quot;)
      }
      .onAppear {
          myData = (try? JSONDecoder().decode([String].self, from: myStoredData)) ?? []
      }
    }
  }
  </code></pre>
  <p>I'm looking for something like this, but this does not work:</p>
  <pre><code>@State var myData : [String] = [&quot;hello&quot;,&quot;world&quot;] {
    didSet {
      myStoredData = try? JSONEncoder().encode(myData)
    }
  }
  </code></pre>
  <pre><code></code></pre>