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

时间:2016-02-09 11:39:08

标签: ios json swift model-view-controller swifty-json

我尝试使用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)时它会返回[Project.Country]并且计数返回1.问题是什么?我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

countriesProject.Country的数组,swift通过打印[Project.Country](包含您的类的一个实例的数组)来表示。没有问题。如果您想证明数组包含Project.Country,则应打印其中一个类属性:print(countries.first.name)

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

答案 1 :(得分:0)

您的问题是您将国家/地区数组传递给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)
                }
            }
相关问题