Search code examples
swiftalamofire

Alamofire empty array


I'm novice programmer and I've been working on movie app and couldn't figure out why Alamofire returns my single parameters from JSON response but doesn't do it in for loop. Here is the code. This function is inside class.

class oneMovie: ObservableObject{
    
    @Published var Movie = Movies()
    
    
    private let API : String
    var url : String
    
    
    init(ID: String){
        self.API = "API"
        self.url = "url.to.somewhere\(ID)"
        MovieGetter(URL: url)
    }



func MovieGetter(URL: String){

        AF.request(URL).responseJSON { (response) in
            
            let json = JSON(response.value!)
        
            if let name         = json["name"].string,
               let description  = json["description"].string
            {
                ///These are stored fine in structure
                self.Movie.name              = name
                self.Movie.description       = description
            }

            for(_, subJson) in json["actors"]{
                if let actorName = subJson["name"].string {

                    ///I can print Actors names but I get nil in actors array in Movie
                    ///structure when I use it
                    
                    print(actorName) //Prints fine
                    self.Movie.actors?.append(actorName)
            }
        }
    }

This is structure

struct Movies {
   
   var name : String?
   var description : String?
   var actors : [String]?

}

Solution

  • It's better to use Codable interface in Swift. Also here is nice description how use that one for Arrays.

    Example:

    struct Movies: Codable {
       
       var name : String?
       var description : String?
       var actors : [String]?
    
    enum CodingKeys: String, CodingKey {
        case name = "name"
        case description = "description"
        case actors = "actors"
      }
    
      init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try response.decode(Bool.self, forKey: .name)
        self.description = try response.decode(String.self, forKey: .description)
        self.actors = try response.decode([String].self, forKey: .actors)
      }
    
      func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try response.encode(self.name, forKey: .name)
        try response.encode(self.description, forKey: .description)
        try response.encode(self.actors, forKey: .actors)
      }
    }