user6539552
user6539552

Reputation: 1451

Loading JSON data as object in SwiftUI

Following the apple developer tutorial on swiftui, https://developer.apple.com/tutorials/swiftui/

I would like to modify it a little bit to include some more fields in the object Landmark:

For example:

struct Landmark: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    var park: String
    var state: String
    var description: String
    var isFavorite: Bool
    var isFeatured: Bool
    var comment: String // example, added this field
}

Yet, for this field, I would like to use it for user to input comment. The String would not be available in the .json file, and hence cannot fill in this information at the stage of "load"-ing the json data.

I found that this will cause error and app crash when this field is not available in the JSON file. How can I resolve this issue? Is that a must that all the fields in the object must appear in the JSON file?

Upvotes: 1

Views: 373

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51861

If only some of the properties in your struct is included in the json then the proper way to tell the encoder/decoder this by adding a CodingKey enum that contains only the json properties and to either make the other properties optional or provide a default value for them.

Since I don't know the original json I have assumed in the below example that the 3 last properties are not included in the json

struct Landmark: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    var park: String
    var state: String
    var description: String
    var isFavorite: Bool = false //use default value
    var isFeatured: Bool = false //use default value
    var comment: String? //make optional

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case park
        case state
        case description
    }
}

Upvotes: 0

Jobert
Jobert

Reputation: 1652

Since the comment field might not be there, you should make it an optional type:

struct Landmark: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    var park: String
    var state: String
    var description: String
    var isFavorite: Bool
    var isFeatured: Bool
    var comment: String? // example, added this field
}

Upvotes: 1

Related Questions