I’m trying to decode a Data object from UserDefaults in a Swift Playgrounds project. Here’s my code:
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!
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:
Using @AppStorage for string map
How can I use @AppStorage for a string map in a SwiftUI app? This is what I want to do: @AppStorage("ratings") var ratings: [String: Double] = [] But this gives me the error message “No ...
stackoverflow.com
Just thought I’d post here in case someone has experience with this, or some idea of what I’m doing wrong. TIA!