Alamofire 空数组 [英] Alamofire empty array

查看:27
本文介绍了Alamofire 空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手程序员,我一直在开发电影应用程序,但无法弄清楚为什么 Alamofire 从 JSON 响应返回我的单个参数,但不在 for 循环中执行此操作.这是代码.这个函数在类里面.

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

这是结构

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

}

推荐答案

最好使用 Codable Swift 中的接口.还有 here 很好地描述了如何将其用于数组.

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

示例:

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

这篇关于Alamofire 空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆