为什么数组 returns nil 在追加元素后?

Why array returns nil after appending to it elements?

我正在尝试使用 JSON 作为 MVC 模型,为此我做了:

// Country.swift
import SwiftyJSON

class Country {
     var code: String!
     var dialCode: Int!
     var name: String!

     init(json: JSON) {
          for i in 0...json["countries"].count - 1 {
             if let code = json["countries"][i]["code2"].string, dialCode = json["countries"][i]["dialCode"].string, name = json["countries"][i]["name"].string {
                 self.code = code
                 self.dialCode = Int(dialCode)
                 self.name = name
             }
         }
     }
 }

后来在我的 ViewController 中我做了:

var countries = [Country]()

Alamofire.request(.POST, "\(property.host)\(property.getCountryList)", parameters: parameters, encoding: .JSON).responseJSON { response in
    do {
        let json = JSON(data: response.data!)
        countries.append(Country(json: json))
    } catch _ {

    }   
}

但我有一个问题。当我打印 Country.swift 文件中的值时,我得到了结果,但是当我 print(countries) 它 returns 我 [Project.Country] 并且计数 returns 1. 问题是什么?我做错了什么?

除非我误解了这不是你想要的行为吗?

countriesProject.Country 的数组,swift 通过打印 [Project.Country] 表示(一个包含 class 的一个实例的数组)。没有问题。如果你想证明数组包含 Project.Country 你应该打印 class' 属性之一:print(countries.first.name)

编辑:问题是您正在将 JSON 个国家/地区数组传递给单个 init 方法,这只是为每个国家/地区设置自身的属性,而不是为每个国家/地区创建一个实例。因此你只返回了一个实例

您的问题是您正在将国家/地区数组传递给 init 方法,该方法只被调用一次,您必须像这里那样做

class Country {
    var code: String!
    var dialCode: Int!
    var name: String!

    init(json: JSON) {
            if let code = json["code2"].string, dialCode = json["dialCode"].string, name = json["name"].string {
                self.code = code
                self.dialCode = Int(dialCode)
                self.name = name
            }
    }
}

然后循环到这里

  Alamofire.request(.POST, "", parameters: nil, encoding: .JSON).responseJSON { response in

                if let jsonResponse = response.result.value{
                    let json = JSON(jsonResponse)

                    for countriesJSON in json["countries"].arrayValue{
                        self.countries.append(Country(json: countriesJSON))
                    }

                    print(self.countries.count)
                }
            }