gpt4 book ai didi

ios - 如何创建自定义结构以将数组内容分配给可用变量?

转载 作者:行者123 更新时间:2023-11-28 16:05:38 25 4
gpt4 key购买 nike

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

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 非常容易出错”,我应该改用自定义结构。

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

谢谢

更新:

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

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 中调用它...接下来的步骤是什么?

最佳答案

与您的想法相同,只是您绘制了整个国家的 map ,而不是绘制每个单独的属性(property)。

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

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

编辑:

在您发布的代码中,您提取了名称和 ID,这就是我将两者都包含在结构中的原因。因此,您可以根据需要从结构中删除 id,或者在将来添加其他变量。然后,当您想要提取它们并在您的 TableView 中使用它们时,您只需执行以下操作:

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

关于ios - 如何创建自定义结构以将数组内容分配给可用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40343981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com