无法用索引“ item”下标“ [item]”的值

时间:2018-06-28 23:11:52

标签: ios arrays json swift

我正在尝试循环遍历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)])), ...])

1 个答案:

答案 0 :(得分:0)

此部分:

for socialIndex in anArray {
    if anArray[socialIndex] != nil {
        //do stuff
    }
}

没有任何意义。

如果您有类型Thing和数组

var array: [Thing] = [thing1, thing2, thing3]

,您使用代码for thing in array { //your code here }

然后变量thing包含您数组中的元素,并且类型为Thing

在代码for socialIndex in anArray中,变量socialIndex将包含数组中的元素,并且属于那些数组元素。

因此,您尝试索引到anArray的位:anArray[socialIndex]无效。

您需要使用Int索引对数组进行索引,并且您已经从数组中提取了元素,所以没有意义。

此代码:

let strings: [String?] = ["now", "is", "the", nil, "time"]

for string in strings {
   if let aString = string {
       print(aString)
   }
}

将输出

now is the time

和代码:

for string in strings {
   if strings[string] != nil { //This makes no sense. `string` is of type String
   }
}

没有道理。