Hi, I have added a property to the Friend struct to indicate whether the friend is also a user so that I can disable the NavigationLink if they are not. I’m trying to set this property in a function (setFriendUserStatus()) after decoding the JSON but I get an error “Cannot assign to property: 'friend' is a 'let' constant” - any help would be much appreciated!
struct User: Identifiable {
let id: String
let isActive: Bool
let name: String
let age: Int
let company: String
let tags: [String]
var friends: [Friend]
enum CodingKeys: CodingKey {
case id, isActive, name, age, company, tags, friends
}
}
extension User: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
isActive = try container.decode(Bool.self, forKey: .isActive)
name = try container.decode(String.self, forKey: .name)
age = try container.decode(Int.self, forKey: .age)
company = try container.decode(String.self, forKey: .company)
tags = try container.decode([String].self, forKey: .tags)
friends = try container.decode([Friend].self, forKey: .friends)
}
}
struct Friend: Identifiable {
let id: String
let name: String
var isUser: Bool = false
enum CodingKeys: CodingKey {
case id, name
}
}
extension Friend: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
}
}
class NetworkManager: ObservableObject {
@Published var users = [User]()
func loadUsersFromURL() {
guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {
print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
return
}
let decoder = JSONDecoder()
do {
let decodedResponse = try decoder.decode([User].self, from: data)
DispatchQueue.main.async {
self.users = decodedResponse
self.setFriendUserStatus()
}
} catch let jsonError as NSError {
print("JSON decode failed: \(jsonError.localizedDescription)")
}
}.resume()
}
func setFriendUserStatus() {
for user in users {
for friend in user.friends {
if let match = users.first(where: {$0.name == friend.name}) {
friend.isUser = true
} else {
friend.isUser = false
}
}
}
}
}