UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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()
    }
}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.