Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Wizec

macrumors 6502a
Original poster
Jun 30, 2019
601
638
I’m trying to decode a Data object from UserDefaults in a Swift Playgrounds project. Here’s my code:

Swift:
import SwiftUI

struct Person: Identifiable, Encodable, Decodable {
    var id = UUID()
    var name = String()
}

struct ContentView: View {
    @State var people: [Person] = [
        Person(name: "Bob")
    ]
    
    init(){
        // decode peopleData from UserDefaults as [Person] into people variable
    guard let people = try? JSONDecoder().decode([Person].self, from: UserDefaults.standard.data(forKey: "peopleData") ?? [Person]())
    else { return }
    }
    
    var body: some View {
        VStack {
            Image(systemName: "person")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            
            ForEach($people, id: \.id){ person in
                HStack{
                    TextField("enter name", text: person.name)
                        .frame(width: 150, height: 40, alignment: .leading)
                        .textFieldStyle(.roundedBorder)
                }
            }
        }
    }
}

I’m getting an error in the JSONDecoder line:

”Cannot convert value of type ‘[Person]’ to expected argument type Data”

I was trying to follow the information from the answer here:


Just thought I’d post here in case someone has experience with this, or some idea of what I’m doing wrong. TIA!
 

Wizec

macrumors 6502a
Original poster
Jun 30, 2019
601
638
Looks like I got it working:

Swift:
import SwiftUI

struct Person: Identifiable, Encodable, Decodable {
    var id = UUID()
    var name = String()
}

struct ContentView: View {
    @State var people: [Person]
    
    init(){
        // decode peopleData from UserDefaults as [Person] into people variable
        if let peopleData = UserDefaults.standard.object(forKey: "peopleData") as? Data{
            people = try! JSONDecoder().decode([Person].self, from: peopleData)
        }
        else {
            people = [
                Person(name: "Fred")
            ]
        }
    }
    
    var body: some View {
        VStack {
            Image(systemName: "person")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            
            ForEach($people, id: \.id){ person in
                HStack{
                    Text("Name")
                        .padding(5)
                        .overlay(RoundedRectangle(cornerRadius: 4).stroke())
                    TextField("enter name", text: person.name)
                        .frame(width: 150, height: 40, alignment: .leading)
                        .textFieldStyle(.roundedBorder)
                }
            }
        }
    }
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.