1

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?

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Even I have made it optional, but if the field is not in the JSON, the app crashes.
Could you share the details of the crash on the console logs?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.