WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

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
         } catch {
         self.name = "x"

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

   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 {


Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.