Im currently learning SwiftUI and I'm having trouble getting my code to print the call from the API
NetworkManager.swift
class NetworkManager: ObservableObject {
@Published var allCountries = Countries()
func fetchAllCountries() {
if let url = URL(string: K.url) {
print(url)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error == nil {
let decoder = JSONDecoder()
if let countriesData = data {
do {
let countries = try decoder.decode(Countries.self, from: countriesData)
DispatchQueue.main.async {
self.allCountries = countries
}
} catch {
print(error)
}
}
}
}
task.resume()
}
}
}
If i print allCountries I can see each item
But on my Main view when I try to print(self.networkManager[5].name) I get an index out of range error
ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var networkManager = NetworkManager()
var body: some View {
Text("Hello, World!")
.onAppear {
self.networkManager.fetchAllCountries()
print(self.networkManager.allCountries[5].name)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Can anyone help point out where I'm going wrong?