Constant '' " used before being initialized

Asked

Viewed 169 times

0

How do I get access to an attribute of one class in another? It may sound silly, but I’m learning now Swift and still getting confused with simple things.

I’m trying to make a movie app using an API. I’m also using Alamofire.

However, this problem when trying to access the id of a movie. In the class I request for api I need to put the movie id together with the url (api prompts you to do so). And I’m having a hard time.

I created a struct that can take all the data that the api returns.

struct DetalhesFilme {

let id: Int
let titulo: String
let nota: Float
let ano: String
let descricao: String
let posterPath: String
let background: String

init(dados: [String: Any]) {

    let media = dados["vote_average"] as! NSNumber
    nota = media.floatValue
    titulo = dados["title"] as! String
    ano = dados["release_date"] as! String
    descricao = dados["overview"] as! String
    posterPath = dados["poster_path"] as! String
    background = dados["backdrop_path"] as! String
    id = dados["id"] as! Int

}

And I made another class that requires it in the API. This is where it is wrong, in Let id = idFilme?. id

Is appearing "Constant 'idFilme' used before being initialized".

class DetalhesAPI {

class func requisicao(completation: @escaping ([DetalhesFilme]) -> Void) {

    let idFilme: DetalhesFilme?
    let id = idFilme?.id   //Constant 'idFilme' used before being initialized
    let filmeDetalhes: [DetalhesFilme] = []

    Alamofire.request("https://api.themoviedb.org/3/movie/\(id)?api_key=4b7fdfc0addcfa48e0168d4bcd77206f", method: .get).responseJSON { (response) in

        switch response.result {
        case .success:
            if let resposta = response.result.value as? Dictionary<String, Any> {
                guard let detalhesLista = resposta as? [[String: Any]] else {
                    return
                }

                completation(filmeDetalhes)

            }
        case .failure:
            print(response.error!)
        }
    }
}

1 answer

0

The error occurs because this object is empty, it was not initialized, you are only declaring the variable. You must pass an id as parameter in this function so that the call returns the detail of the movie you are waiting for as:

class func requisicao(id: Int, completation: @escaping (Result<DetalhesFilme>) -> Void) { ...

Taking advantage of some improvements to facilitate the use of this code, the first is to use the Codable protocol to facilitate the conversion of the response to Object, follows the code to the class:

struct DetalhesFilme: Codable {

    let id: Int
    let titulo: String
    let nota: Float
    let ano: String
    let descricao: String
    let posterPath: String
    let background: String

    enum CodingKeys: String, CodingKey {
        case id
        case titulo = "title"
        case nota = "vote_average"
        case ano = "release_date"
        case descricao = "overview"
        case posterPath = "poster_path"
        case background = "backdrop_path"
    }
}

Another important thing is to put the . responseData in the place of . responseJSON because it will facilitate the conversion of the answer to object:

class DetalhesAPI {

    class func requisicao(id: Int, completation: @escaping (Result<DetalhesFilme>) -> Void) {

        Alamofire.request("https://api.themoviedb.org/3/movie/\(id)?api_key=4b7fdfc0addcfa48e0168d4bcd77206f", method: .get).responseData { (response) in
             switch response.result {
                        case .success(let data):
                            do {
                                let detail = try JSONDecoder().decode(DetalhesFilme.self, from: data)
                                completation(.success(detail))
                            } catch {
                                 completation(.failure(error))
                            }
                        case .failure(let error):
                            completation(.failure(error))
                        }
                    }
        }
}

Use of the code:

DetalhesAPI.requisicao(id: 32) { (result) in
    switch(result){
    case .success(let detalhe):
        // Aqui você tem o objeto recebido
        print(detalhe)
    case .failure(let error):
        // Aqui você trata o erro caso ocorra
        print(error)
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.