0

I have a large number of structs that are being populated by decoding JSON data. I want the system to be robust and handle optional keys in the JSON. This leaves me with a lot of optional unwrapping code in my UI.

struct SomeStruct: Decodable {
    public var id: Int
    public var firstName: String?
    public var lastName: String?
}

Text("\(someStruct.lastName ?? ""), \(someStruct.firstName ?? "")")

I am looking for a clean way to set defaults and avoid unwrapping theses optionals throughout my UI layer. For example someone gave this solution: https://stackoverflow.com/a/57260118. This would work but would also create a ton of near duplicate code. Does anyone have a more elegant solution to this? The success criteria is JSON -> struct parsing with a minimal required keys and removing optional unwrapping from the UI code.

Jaybit
  • 1,864
  • 1
  • 13
  • 20
  • Is there a difference between “” and nil for firstName in your app? – Lou Franco Sep 25 '19 at 01:01
  • @LouFranco the empty quotes "" were dropped in just for example it might be "NA" or "Unknown" but yes nil would not work in this case. I am looking to have Text("\(someStruct.lastName), ... without having to unwrap the optional in the UI layer. – Jaybit Sep 25 '19 at 01:14
  • I would use the computed property approach shown in the answer by @Cristik in that same question – Paulw11 Sep 25 '19 at 02:00
  • 1
    Does this answer help: https://stackoverflow.com/a/54973831/1974224? – Cristik Sep 25 '19 at 05:21
  • @Cristik It is nearly the same solution where all the code needs to be duplicated but I do like that it is bundled within a single struct. – Jaybit Sep 25 '19 at 17:12

0 Answers0