I needed to ask a query about my doubt.
I am presently implementing my code for decoding a JSON
file utilizing two buildings for the info mannequin and one FriendsManager
class for knowledge administration
In your opinion is that this method or ought to I work with structs
as a substitute of utilizing a class
?
I am new to decoding JSON
recordsdata and needed to ensure I used to be writing my code the appropriate approach
non-public let JSONFriendFileName = "Pals"
class FriendsManager: ObservableObject {
var friendsList: [FriendsList] = []
init() {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decode(fileName: JSONFriendFileName, decoder: decoder)
}
func decode(fileName: String, decoder: JSONDecoder) {
guard let url = Bundle.essential.url(forResource: JSONFriendFileName, withExtension: "json") else {
print("Non esiste alcun file denominato (JSONFriendFileName + ".json") in questo progetto")
return
}
do {
let knowledge = strive Information(contentsOf: url)
let objects = strive decoder.decode(Pals.self, from: knowledge)
friendsList = objects.friendsList
} catch {
print(error.localizedDescription)
}
}
}
struct Pals: Codable {
var friendsList: [FriendsList]
}
struct FriendsList: Codable, Identifiable {
let title: String
let timestamp: Int?
let contact_info: String?
let id = UUID()
enum CodingKeys: String, CodingKey {
case title, timestamp, contact_info
}
}
Information utilization
import SwiftUI
struct FriendsView: View {
@StateObject non-public var friendsManager = FriendsManager()
var physique: some View {
NavigationView {
Listing {
ForEach(friendsManager.friendsList) { pals in
Textual content(pals.title)
}
}
.navigationTitle("Pals")
}
}
}