以下回复中如何检查数据密钥?

时间:2016-07-14 07:29:04

标签: ios iphone swift cocoa-touch cocoapods

我在swift中使用ObjectMapper.framework并成功映射了所有值。那是我的代码

class CompetitionListModel: Mappable {
var active: Int?
var channel: String?
var competition_type_id: Int?
var country_id: Int?
var created_at: [String: String]?
var ends_at: String?
var id: Int?
var name: String?
var logo: String?
var order: Int?
var parent: Int?
var updated_at: String?
var data: [AnyObject]?


required init?(_ map: Map) {
    mapping(map)
}

func mapping(map: Map) {
    active <- map["active"]
    channel <- map["channel"]
    competition_type_id <- map["competition_type_id"]
    id <- map["id"]
    country_id <- map["country_id"]
    created_at <- map["created_at"]
    ends_at <- map["ends_at"]
    name <- map["name"]
    logo <- map["logo"]
    order <- map["order"]
    parent <- map["parent"]
    updated_at <- map["updated_at"]
    data <- map["data"]


}
}

以下是我映射的回复

   {
    active = 1;
    channel = fieldhockey;
    "competition_type_id" = 2;
    "country_id" = 2;
    "created_at" = "2014-09-19T14:45:43";
    "ends_at" = "2099-09-19T00:00:00";
    id = 31;
    logo = "cf78a0a5-9ee2-4419-87e7-90b2eacf6ff5.png";
    name = Fieldhockey;
    order = "-2";
    parent = 0;
    "updated_at" = "2015-09-10T09:30:33";
},
    {
    active = 0;
    channel = "fh-eurohockey-u18m-championship2";
    "competition_type_id" = 2;
    "country_id" = 2;
    "created_at" = "2015-07-02T18:03:50";
    data =         {
    };
    "ends_at" = "2099-12-31T00:00:00";
    id = 112;
    logo = "a19945fd-a0db-485f-809d-d6078e7fbfe8.jpg";
    name = "EuroHockey U18 Championship II, Boys, 2015";
    order = "-2";
    parent = 31;
    "updated_at" = "2015-09-10T09:26:56";
},

我通过此代码获取此值

var arrOperation: [CompetitionListModel] = []

并通过此获取arrOperation的值     打印(self.arrOperation [0]。数据)

但您可以在响应中看到数据键在此响应中有时不出现,有时则出现。所以我必须检查数据键是否存在,但我也映射了这个键,它也始终存在于模型类中。所以我正在检查此代码

     if  let keyExists = self.arrOperation[indexPath.row].data {
      print("key is present")
    }
    else{
        print("key is not present")

    }

但数据键始终在模型类中显示其打印nil值。所以请告诉我如何识别数据的关键名称是否存在于数组中。

1 个答案:

答案 0 :(得分:3)

for dict in self.arrOperation {
    if  let keyExists = dict["data"] {
        print("key is present")
    }
    else{
        print("key is not present")

    }
}

试试这段代码。对于我的字典中有一个数据键,这段代码工作正常