如何创建自定义结构以将数组的内容分配给可用变量? [英] How do I create a custom struct to assign the contents of array into usable variables?

查看:104
本文介绍了如何创建自定义结构以将数组的内容分配给可用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON函数,该函数先前使用以下代码将数组(countriesdivisionsteams(未显示))的内容映射到单独的变量中:

I have a JSON function that previously mapped the contents of an array (countries, divisions, teams (not shown)) into seperate variables using this code:

let task = URLSession.shared.dataTask{ (response: URLResponse?, error: Error?) in

        DispatchQueue.main.async
            {

                if error != nil {
                    print("error=\(error)")
                    return
                }

                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                        print (json)

                        if let arr = json?["countries"] as? [[String:String]] {
                            self.countryId = arr.flatMap { $0["id"]!}
                            self.countries = arr.flatMap { $0["name"]!}
                            self.teamsTableView.reloadData()
                            print ("Countries: ",self.countries)
                        }

                    if let arr = json?["divisions"] as? [[String:String?]] {

                        self.divisions = arr.flatMap { ($0["name"]! )}
                        self.divisionId = arr.flatMap { ($0["id"]! )}
                        self.teamsTableView.reloadData()
                        print ("Divisions: ",self.divisions)
                    }



                } catch{
                    print(error)
                }
        }
    }

但是,自那以后,我学会了将多个数组作为数据源与flatMap一起映射很容易出错",我应该改用自定义结构.

However, I have since learned "that mapping multiple arrays as data source in conjunction with flatMap is pretty error-prone", and that I should use a custom struct instead.

如何/从哪里开始编写自定义结构,以将此JSON数组的内容分配给单独的变量?

How / Where do I begin to write a custom struct to assign the contents of this JSON array into seperate variables?

谢谢

更新:

我使用了下面建议的代码,我相信这是正确的.下面是当前输出.

I have used the code as suggested below and I believe this is along the right lines. Below is the current output.

国家/地区:[KeepScore.SumbitScoreViewController.Country(名称:Optional(丹麦"),countryId:Optional("1")),KeepScore.SumbitScoreViewController.Country(名称:Optional(比利时"),countryId:可选( "2")),KeepScore.SumbitScoreViewController.Country(名称:Optional(巴西"),countryId:可选("3")),

Countries: [KeepScore.SumbitScoreViewController.Country(name: Optional("Denmark"), countryId: Optional("1")), KeepScore.SumbitScoreViewController.Country(name: Optional("Belgium"), countryId: Optional("2")), KeepScore.SumbitScoreViewController.Country(name: Optional("Brasil"), countryId: Optional("3")),

但是,从外观上看,它也将countryId放入变量中,而我只需要名称,这样我就可以在UITable中调用它了……下一步要做什么? >

However by the looks of it, it is also putting the countryId into the variable and I'd like just the name so I could call it in a UITable...What are the next steps in doing this?

推荐答案

与您所做的想法相同,不同之处在于,您不是在绘制每个国家/地区的地图,而是在整个国家/地区绘制地图.

Same idea as you were doing, except instead of mapping each individual property you map the whole country.

//define a struct
struct Country {
    var name: String?
    var countryId: String?

    init(_ dictionary: [String : String]) {
        self.name = dictionary["name"]
        self.countryId = dictionary["id"]
    }
}

//defined in your class
var countries = [Country]()

//when parsing your JSON
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json)

if let arr = json?["countries"] as? [[String : String]] {
    self.countries = arr.flatMap { Country($0) }
    print ("Countries: ",self.countries)
}

将相同的想法应用于部门.

Apply the same idea to divisions.

在您发布的代码中,您同时提取了名称和ID,这就是为什么我在结构中都包含了这两个原因的原因.因此,您可以根据需要从结构中删除ID,也可以在以后添加其他变量.然后,当您要提取它们并在表视图中使用它们时,只需执行以下操作:

In the code you've posted, you extract both the name and the id, that's why I included both in the struct. So you can remove the id from the struct if you wish, or add other variables in the future. Then when you want to extract them and use them in your table view you just do:

let country = countries[indexPath.row]
cell.textLabel.text = country.name

这篇关于如何创建自定义结构以将数组的内容分配给可用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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