NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SwiftUI - decode JSON into @State variable question (Hot Prospects project)

Forums > Books

This may be a case where I may not be understanding clearly how State variables function. I'm working on a challenging from the Hot Prospects project to save/load user data using JSON (below is simplified code to show issue).

Encoding seems to work fine. Decoding also seems to work. However, the decoded value isn't getting into the State name variable. My print statements show the decoding working, but the assignment is not.

I could also be making it more complicated than it needs to be...

Any help appreciated. Thanks.

struct ContentView: View, Codable {
   @State private var name = ""
   static let saveKey = "testData"

   enum CodingKeys: CodingKey {
      case name
   }

   init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      name = try! container.decode(String.self, forKey: .name)

      print("name: \(name)") // name is empty
      print(try! container.decode(String.self, forKey: .name)) // prints name showing value can be decoded correctly, so encoding is also OK.
   }

   func encode(to encoder: Encoder) throws {
      var container = encoder.container(keyedBy: CodingKeys.self)
      try container.encode(name, forKey: .name)
   }

   init() {
      if let data = UserDefaults.standard.data(forKey: Self.saveKey) {
         do {
            let result = try JSONDecoder().decode(Self.self, from: data)
            print("decoded: \(result)")
               self = result
             //  self.name = result.name
               return
         } catch {
            print(error.localizedDescription)
         }
         self.name = "x"
      }
   }

   var body: some View {
      TextField("Name", text: $name)
         .onChange(of: name) { value in
            save()
         }
   }

   func save() {
      if let encoded = try? JSONEncoder().encode(self) {
         UserDefaults.standard.set(encoded, forKey: Self.saveKey)
      }
   }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.