Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'

前端 未结 2 1205
执念已碎
执念已碎 2020-12-17 18:01

I\'m trying to get some data from a JSON content(in my data.swift file) and assign it to \"comments\". Anyone know whats going wrong here and how I can fix it? Seems like a

相关标签:
2条回答
  • 2020-12-17 18:15

    According to your own declaration, story is a [String:AnyObject]. That means that story["comments"] is an AnyObject. But comments is a [String:AnyObject], not an AnyObject. You can't assign an AnyObject where a [String:AnyObject] is expected.

    0 讨论(0)
  • 2020-12-17 18:25

    There is an error in your code, but the error message you're seeing is incorrect and misleading due to a Swift compiler bug. The actual error message should read: AnyObject is not convertible to [String:AnyObject].

    self.story["comments"] returns an AnyObject. To assign that value to self.comments you must first typecast AnyObject to the Dictionary type [String:AnyObject].

    For example:

    self.comments = self.story["comments"] as! [String:AnyObject]
    
    0 讨论(0)
提交回复
热议问题