user14848647
user14848647

Reputation:

how to check key of json data exists or not in SwiftUI?

Could you help me, please? How to check a key of json data “subtitle” exits or not ?

 //Model.swift
  import Foundation
var data: [Post] = load("song.json”)
 ......

//Post.swift
struct Post: Codable, Hashable{
    var id: Int
    var title: String
    var subtitle: String
    var body: String
     }

I got json data value like this:

 Text(data[index].title)

.

[
  {
  “id”:1,
  “title”:”Title Value”,
  “body”:”Body Value"
   }
    ,
    {
      “id”: 1,
  “title”: ”Title Value”,
   “subtitle”:” SubTitle Value”,
      “body”: “Body Value"

     } ,etc.. 
  ]

Upvotes: 0

Views: 395

Answers (1)

Asperi
Asperi

Reputation: 257779

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)
  }
}

Upvotes: 3

Related Questions