Swift:“类型'Any'的值没有下标”错误/ Swift 5

时间:2019-06-03 23:19:21

标签: swift

以下代码将显示“ Any类型的值没有下标”

if let postDictionary = jsonDictionary["post"] as? [String: AnyObject]
class FeedController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    var posts = [Post]()

    override func viewDidLoad() {
        super.viewDidLoad()

        if let path = Bundle.main.path(forResource: "single_post", ofType: "json") {
            do {
                let data = try(NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe))

                let jsonDictionary = try(JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers))

                if let postDictionary = jsonDictionary["post"] as? [String: AnyObject] {
                    let post = Post()
                post.setValuesForKeysWithDictionary(postDictionary)
                    self.posts = [post]
                }

                print(jsonDictionary)
            } catch let err {
                print(err)
            }
        }

1 个答案:

答案 0 :(得分:0)

jsonObject(with:options:)返回Any

您需要先将其转换为[String: AnyObject]类型。

更改:

if let postDictionary = jsonDictionary["post"] as? [String: AnyObject]

收件人:

if let dictionary = jsonDictionary as? [String: AnyObject], let postDictionary = dictionary["post"] as? [String: AnyObject]

文档: https://developer.apple.com/documentation/foundation/jsonserialization/1415493-jsonobject