如何从多层嵌套JSON结构中获取Properties结构体的title属性值
问题排查与解决方案
- 你的代码存在两个可调整点:
- 可选值解包后使用错误:你已经通过
if let result = results完成了可选值安全解包,但后续遍历仍使用了未解包的results.features,属于不规范的可选值访问。 - 模型层级遍历不完整:
Features结构体中的properties是[Properties]数组类型,要拿到title属性需要对properties数组做二次遍历。
- 可选值解包后使用错误:你已经通过
调整后的完整代码
getJSON(urlString: urlString) { (results: main?) in // 安全解包根模型 guard let mainModel = results else { return } // 遍历features数组 for feature in mainModel.features { print(feature.something) // 二次遍历当前feature下的properties数组 for property in feature.properties { print(property.title) } } }
补充说明
如果你的实际JSON结构中properties对应的是单个对象而非数组,需要先修正模型定义:
struct Features: Decodable{ let something: String // 把数组类型改成单个Properties类型 let properties: Properties }
此时不需要二次遍历,直接访问即可:
print(feature.properties.title)
内容的提问来源于stack exchange,提问作者wyOhmy
相关产品推荐
相关产品推荐

