UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?
}

2      

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)?

2      

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.

3      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.