arrays - 在控制台中获得基础结果后,如何将它们放入结构中?
问题描述
我完成了从 JSON 中提取控制台中的三个数组(名称、艺术家和价格)的结果的整个过程。现在我需要将它们放在一个结构数组中,我将使用它来最终填充我的 tableView。我被困在这里。
我试图将控制台中的最终常量字符串分配为 struct 属性的参数。我想,然后我可以将它们用于 append 方法来完成我的结构数组。我在这里错过了一些东西。我无法填充我的数组。我没有在 Swift 3 中使用实际的 Codable 协议,因为我认为在攻击最后的 Swift 更新之前清楚地理解它对我的学习很重要。
do{ if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [字符串:任何] {
let results = json as? [String: Any]
if let feed = results!["feed"] as? [String: Any]{
if let entry = feed["entry"] as? [[String: Any]]{
for item in entry{
if let price = item["im:price"] as? [String: Any]{
if let labelPrice = price["label"] as? String{
print(labelPrice)
self.topTen.songPrice = labelPrice
}
}
}
for item2 in entry{
if let name = item2["im:name"] as? [String: Any]{
if let labelName = name["label"] as? String{
print(labelName)
self.topTen.name = labelName
}
}
}
for item3 in entry{
if let artist = item3["im:artist"] as? [String: Any]{
if let labelArtist = artist["label"] as? String{
print(labelArtist)
self.topTen.artist = labelArtist
}
}
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
catch{
print(error.localizedDescription)
}
}
task.resume()
}
如果我插入: topTenArray.append((TopTen(name: topTen.name, artist: topTen.artist, songPrice: topTen.songPrice))) ,我也无法填充数组。
解决方案
您需要将结构对象创建到局部变量并将该对象附加到您的数组中,如下所示。并且不需要在同一个对象上进行多个循环。你可以这样做。
let results = json as? [String: Any]
if let feed = results!["feed"] as? [String: Any] {
if let entry = feed["entry"] as? [[String: Any]] {
for item in entry {
let topTen = YourTopTenStructure()
if let price = item["im:price"] as? [String: Any]{
if let labelPrice = price["label"] as? String{
print(labelPrice)
topTen.songPrice = labelPrice
}
}
if let name = item["im:name"] as? [String: Any]{
if let labelName = name["label"] as? String{
print(labelName)
topTen.name = labelName
}
}
if let artist = item["im:artist"] as? [String: Any]{
if let labelArtist = artist["label"] as? String{
print(labelArtist)
topTen.artist = labelArtist
}
}
topTenArray.append(topTen)
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
catch{
print(error.localizedDescription)
}
}
task.resume()
推荐阅读
- perl - 在线程之间共享队列管理器连接
- java - java.lang.NoSuchMethodError:javax/ws/rs/core/MultivaluedMap.addAll
- c# - 自定义模型绑定器 asp.net 核心绑定字典
- python - 具有不同 x 和 y 编码的 Altair 选择
- r - 如何测试具有缺失值的多元正态性?
- r - 如何在运行时在 ggplot2 中添加行?
- google-bigquery - 在 BigQuery 上的一个查询中对所有列进行重复数据删除
- filepond - 无法在文件池中看到图像的预览
- terraform - “aws_cloudformation_stack”的 Terraform 不支持的块类型错误
- c++ - 我应该在下面添加什么代码进行同步?