swift - 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)
}
}
解决方案
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
推荐阅读
- python - 使用列表使目标在与子弹碰撞时消失
- javascript - 将嵌套的 AJAX 调用转换为顺序 Promise
- swift - 如何创建在 Swift 中可全局访问的结构?
- sql - 使用 SQL 旋转结果
- php - How to create a form that accept number only
- graph - Highchart - ThingSpeak - IoT - 图表(轴)问题
- snowflake-cloud-data-platform - 查找对象何时在雪花中掉落
- wxwidgets - 为 FileZilla 编译“构建 wxWidgets”时出错:配置:错误:未找到 X11,请使用 --x-includes 和/或 --x-libraries 选项
- java - 为什么我从另一个 Activity 传递的列表中获取空值?
- android - 我不明白为什么响应成功后没有触发“onResponse()”?