首页 > 解决方案 > 如何在 SwiftUI 中检查 json 数据的键是否存在?

问题描述

标签: swiftswiftuiswift5xcode12

解决方案


Make subtitle optional in model and use it conditionally in view, like

struct Post: Codable, Hashable{
    var id: Int
    var title: String
    var subtitle: String?     // << this !!
    var body: String
}

and somewhere in body:

VStack(alignment: .leading) {
  Text(data[index].title)
  if let subtitle = data[index].subtitle {
    Text(subtitle)
  }
}

推荐阅读