Home > Software engineering >  How to check JSON for key value pairs missing, with Swiftui
How to check JSON for key value pairs missing, with Swiftui

Time:02-26

I've parsed a JSON from YouTube and not every item in the array necessarily have certain Key:Value pairs, thus I get a fatal error. My only solution has been to comment out certain key:values from my Model. However I'd like a more appropriate solution but I'm not sure the right way to dynamically guard for missing key:values.

Can anyone help me with a method for doing this in swiftui.

CodePudding user response:

First, decoding a JSON is not specific to SwiftUI, the only time SwiftUI is used is when interacting with the User Interface.

You can use something like below in a custom initializer for your struct or class

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    latitude = try values.decodeIfPresent(Double.self, forKey: .latitude)
}

A decoded value of the requested type, or nil if the Decoder does not have an entry associated with the given key, or if the value is a null value.

https://developer.apple.com/documentation/swift/keyeddecodingcontainer/2893445-decodeifpresent

Below is the Apple documentation on decoding and encoding custom types

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

  • Related