1

I am trying to use @AppStorage on custom property wrapper like this:

@AppStorage("imports") var name: [NameSection]

My app works normal without the @AppStorage("imports").

I keep getting this "No exact matches in call to initializer" error when add the @AppStorage

I know that the error is caused due to not using the Property Wrappers Supported.

I have looked at these links for reference but all these once are using the data types, so none of them helped: Using @AppStorage for string map 'No exact matches in call to initializer' error on @AppStorage variable? SwiftUI: What is @AppStorage property wrapper

All I am trying to do is save the data in AppStorage once its decoded

Here is my decoder for my NameSection:

                 VStack (spacing: 30) {
                        Button(action: {imported.toggle()}, label: {
                            Text("Import")
                            Image(systemName: "square.and.arrow.down")
                        })
                    }
                    .fileImporter(isPresented: $imported, allowedContentTypes: [.json]) { res in
                        do {
                            let fileUrl = try res.get()
                            if fileUrl.startAccessingSecurityScopedResource() {
                                let fileData = try Data(contentsOf: fileUrl)
                                defer  { fileUrl.stopAccessingSecurityScopedResource() }
                                let importedNames = try? JSONDecoder().decode([NameSection].self, from: fileData)
                                name = importedNames ?? []
                                importDone = true
                            }else{
                                
                            }
                        } catch{
                            print (error.localizedDescription)
                        }
                    }

And here is the struct for my NameSection:

struct NameSection: Codable, Identifiable, Hashable {
    var id: UUID
    var name: String
    var items: [NameItem]
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

struct NameItem: Codable, Equatable, Identifiable {
    var id: UUID
    var name: String

    static let example = NameItem(id: UUID(), name: "Geeth Gunnampalli")

    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}
geethsg7
  • 205
  • 2
  • 11
  • Have you tried adding a default value to your declaration? e.g., `@AppStorage("imports") var name: [NameSection] = []` – ScottM May 31 '21 at 18:52
  • I used it a bit different in one of my applications. I went for something like this; `@Appstorage("imports") var name: Data = Data()` Then I use a `JSONEncoder` to encode my custom struct to a `Data` object. Then whenever I need it, I decode it using a JSONDecoder. – Wouter May 31 '21 at 19:05
  • yeah I tried both none of them work in my case. – geethsg7 May 31 '21 at 20:15

0 Answers0