Hello
I'm trying to decode a JSON File but it's not working and I can't understand why
Code:
Here is the JSON file
Thank you
I'm trying to decode a JSON File but it's not working and I can't understand why
Code:
Code Block import SwiftUI struct Search: View { let sf: [SF] = Bundle.main.decode("sf.json") @State private var searchText: String = "" var body: some View { NavigationView{ Form { Section(header: Text("Search bar")){ TextField("Search", text: $searchText) .padding(7) .background(Color(.systemGray6)) .cornerRadius(8) } Section(){ List{ ForEach(sf) { item in Text(item.title) } } } } .navigationTitle("SF") } } } struct SF: Codable, Identifiable { var id: String var title: String var items: [String] } extension Bundle { func decode<T: Codable>(_ file: String) -> T { guard let url = self.url(forResource: file, withExtension: nil) else { fatalError("Failed to locate \(file) in bundle.") } guard let data = try? Data(contentsOf: url) else { fatalError("Failed to load \(file) from bundle.") } let decoder = JSONDecoder() guard let loaded = try? decoder.decode(T.self, from: data) else { fatalError("Failed to decode \(file) from bundle.") } return loaded } }
Here is the JSON file
Code Block [ { "id": "all" "title": "All", "items": [ "square.and.arrow.up", "square.and.arrow.up.fill", "square.and.arrow.down" ] } ]
Thank you
Apparently, it does not have "id" in any elements.This is the file now:
You can remove id as a stored property from SF to make your file decodable,
and add another computed property id to make it conform to Identifiable:
Code Block struct SF: Codable, Identifiable { //var id: String //<- Remove this stored property var id: String {title} //<- Add this computed property var title: String var items: [String] }
That is not for this thread. Please keep, one thread for one topic.And I have another question about the decimalPad