【发布时间】:2018-06-28 23:11:52
【问题描述】:
我正在尝试循环遍历 JSON 结构中的数组,但无论我做什么,我都会收到错误“无法使用 'item' 类型的索引下标 '[item]' 类型的值。我可以每当我分别调用每个索引时打印它:
self.socialTitle = (storeSocialContext.items?[1].metatags?.first?.title)!
print(self.socialTitle)
这给了我一个字符串,我想要它。但我想要每个索引的字符串,作为标题。 这是给出错误的循环:
var anArray = storeSocialContext.items!
for socialIndex in anArray {
if anArray[socialIndex] != nil {
}
}
这是结构:
struct StoreSocialContext: Decodable
{
var items: [Item]?
}
struct Item: Decodable
{
var metatags: [enclosedTags]?
enum CodingKeys : String, CodingKey
{
case pagemap
}
enum PageMapKeys: String, CodingKey
{
case metatags
}
init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)
let pagemap = try values.nestedContainer(keyedBy: PageMapKeys.self, forKey: .pagemap)
metatags = try pagemap.decode([enclosedTags].self, forKey: .metatags)
}
}
struct enclosedTags: Decodable
{
let image: String?
let title: String?
let description: String?
let siteName: String?
private enum CodingKeys : String, CodingKey
{
case image = "og:image", title = "og:title", description = "og:description", siteName = "og:site_name"
}
}
这是我在控制台中获取和打印 JSONdata 时的数据片段:
Optional([GetContext.Item(metatags: Optional([GetContext.enclosedTags(image:
nil, title: nil, description: nil, siteName: nil)])), GetContext.Item(metatags:
Optional([GetContext.enclosedTags(image: Optional("https://www.merriam-
webster.com/assets/mw/static/social-media-share/mw-logo-245x245@1x.png"),
title: Optional("Definition of BEST"), description: Optional("excelling all
others; most productive of good : offering or producing the greatest advantage,
utility, or satisfaction; most, largest… See the full definition"), siteName:
nil)])), ...])
【问题讨论】:
-
什么是
socialTry?为什么将Item数组分配给名为socialItem的变量而不是socialItems?在您的for循环中,为什么将单个Item分配给名为socialIndex的变量?更好的变量命名将使您的代码更易于阅读,并使您的问题更易于解决。 -
Tnx,我编辑了它。我在输入问题时弄乱了变量。希望现在更清楚了。如果没有,请告诉我。
-
for-in 循环遍历数组中的项目,而不是索引。因此,除非您需要索引本身的某些内容,否则您已经拥有您的项目并且不需要下标任何内容。见docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
-
除了问题之外,
nil检查毫无意义。该数组不包含任何选项。