Alamofire 空数组

Alamofire empty array

我是新手程序员,我一直在开发电影应用程序,但无法弄清楚为什么 Alamofire returns 我的单个参数来自 JSON 响应,但没有这样做环形。这是代码。这个函数在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)
            }
        }
    }

这是结构

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

}

您需要先初始化数组。请参考以下代码:

var actors = [String]()
for(_, subJson) in json["actors"]{
    if let actorName = subJson["name"].string {
        actors.append(actorName)
    }
}
self.Movie.actors = actors

最好使用 Codable interface in Swift. Also here 很好地描述了如何将它用于数组。

示例:

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