首页 > 解决方案 > Swift:“'Any'类型的值没有下标”错误/ swift 5

问题描述

以下代码将显示“'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)
            }
        }

标签: swift

解决方案


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


推荐阅读