I'm new to SwiftUI and any help will be appreciated.
I have a Json file:
[
{
"id": 1001,
"key1": "truck",
"key2": "car1",
"key3": "motorcycle",
},
{
"id": 1002,
"key1": "truck",
"key2": "car2",
"key3": "motorcycle",
},
{
"id": 1003,
"key1": "truck",
"key2": "car2",
"key3": "motorcycle",
},
{
"id": 1004,
"key1": "truck",
"key2": "car2",
"key3": "motorcycle",
},
{
"id": 1005,
"key1": "truck",
"key2": "car3",
"key3": "motorcycle",
},
]
I can reach values like this:
VStack{
ForEach(userData.vehicles) { vehicle in
Text(vehicle.key2)
.foregroundColor(.white)
}
}
The output is:
car1
car2
car2
car2
car3
What I want to see is:
car1
car2
car3
Is there any way to group the keys in SwiftUI?
Edit: @MahdiBM requested the following codes in comment section.
Vehicle declaration
final class UserData: ObservableObject {
@Published var showFavoritesOnly = false
@Published var vehicles = vehicleInfo
}
Reading Json
let vehicleInfo: [Vehicle] = readJSON("vehicleInfo.json")
func readJSON<T: Codable>(_ named: String) -> T {
if let resPath = Bundle.main.resourcePath {
do {
let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let filteredFiles = dirContents.filter{ $0.contains(".json")}
for fileName in filteredFiles {
if let documentsURL = documentsURL {
let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
let destURL = documentsURL.appendingPathComponent(fileName)
do {
try FileManager.default.copyItem(at: sourceURL, to: destURL)
print("Save to documents")
} catch {
print("ERROR FileManager.default.copyItem:: ", error)
}
}
}
}catch { print("ERRIR 2", error) }
}
let data: Data
do {
let fileURL = try FileManager.default
.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("vehicleInfo.json")
data = try Data(contentsOf: fileURL)
let foo = try JSONDecoder().decode(T.self, from: data)
// print(foo)
return foo
} catch {
fatalError("Couldn't find in main bundle.")
}
}
Edit 2:
struct Vehicle: Hashable, Codable, Identifiable {
var id: Int
var key1: String
var key2: String
var key3: String
}
SO says; "It looks like your post is mostly code; please add some more details."
They need to review this requirement I believe, because there is nothing I can say more.
struct Vehicle { var key1: String ...... }. This above code looks good though and at first glance doesn't have any real problems.