the people if let seems to print the json people[0].login fine but users is empty which I need to store the json so I can use it elsewhere in the app. I want the users var to get populated so it can actually be useful to me and not crash because there is nothing when I try to use it on the table view in the view controller. I can't use people outside of the scope of the if let.
import Foundation
final class UsersListViewModel {
var users = [Users]()
init() {
fetchData()
}
func fetchData() {
let url = URL(string: "https://api.github.com/users")!
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
print(error?.localizedDescription ?? "Unknown error")
return
}
let decoder = JSONDecoder()
if let people = try? decoder.decode([Users].self, from: data) {
DispatchQueue.main.async {
self.users = people
print("Loaded \(people.count) users.")
print(people[0].login)
print(people[1].login)
}
} else {
print("Unable to parse JSON response.")
}
}.resume()
}
}