WWDC21 SALE: Save 50% on all my Swift books and bundles! >>

SwiftUI and JSON Class file

Forums > SwiftUI

What is wrong here?

Error : Cannot assign of type [Result] to type Response

class NetworkManager: ObservableObject {
    var didChange = PassthroughSubject<NetworkManager, Never>()

    var data: Response{
        didSet {
            didChange.send(self)
        }
    }

    init() {
        guard let url = URL(string: "http://www.dqma.dk/football.json") else {
            return
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                    DispatchQueue.main.async {
                        self.data = decodedResponse.data
                    }
                    return
                }
            }
        }.resume()
    }
}

struct Response: Decodable {
    var data: [Result]
}
struct Result: Codable {
    var match_id: Int
    var match_start: String
    var status: String
    var home_team: home_team
    var away_team: away_team
    var stats: stats?
}
struct home_team:  Codable {
    var team_id: Int
    var name: String
    var logo: String
}
struct away_team:  Codable {
    var team_id: Int
    var name: String
    var logo: String
}
struct stats:  Codable {
    var ft_score: String?
}

   

I'm new at this, but wondering if snake_case creates any problem, as I think Swift wants camelCase. Or does Swift need the variables appear in the order in which the JSON keys appear (even if you don't need to include all of them)?

   

This is the problem: self.data = decodedResponse.data

self.data is of type Response but you are assigning a Response.data, which is of type [Result].

self.data either needs to be of type [Result] or the offending line should be changed to self.data = decodedResponse, whicever works best for your use case.

1      

I am suprised that it worked because the URL that you are using is not https and you should get this error

URLError: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

   

Save money with our WWDC sale!

SAVE 50% To celebrate WWDC21, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.