0

How do I initialize a nested struct in SwiftUI? This struct will be populated after parsing JSON from a RESTAPI, but i want to make it available as Observable so my view can access it later when data is populated.

final class APIController: ObservableObject { 
@Published var iotshadow: IotShadow

IotShadow is the nested struct of a few levels. To line by line assign it a default value seems very excessive. Also if I leave it as optional IotShadow? then I don't seem to be allowed to access it as it complains that the value need to be unwrapped.

What would be the correct way to initialize a struct in this case? New to Swift but experienced Java/C programmer so maybe I am thinking in the wrong way here.

Thanks, Marcus

4
  • If you define it as optional (with a ?) then yeah, you would have to check it’s not nil before accessing it. I’d recommend reading up on Swift optionals. Can you show the code/error you are getting about unwrapping. Thanks Commented Dec 30, 2021 at 9:05
  • @Fogmeister This it the error I am getting "Value of optional type 'IotShadow?' must be unwrapped to refer to member 'state' of wrapped base type ‘IotShadow'" and it comes from the print statement iotshadow = try! JSONDecoder().decode(IotShadow.self, from: jsonData) print("Reported Relay1: \(iotshadow.state.desired.RELAY1)") Commented Dec 30, 2021 at 9:09
  • 1
    IotShadow is optional so I think you would need to add a ? After iotShadow in your print line. Definitely read up on how to use optional though. They are central to all development in Swift. It’s def important to know how and why to use them. 👍🏻 Commented Dec 30, 2021 at 9:12
  • @Fogmeister, thanks that actually did it, I will take your suggestion and read up on optionals to get a better understanding of how to handle them. Commented Dec 30, 2021 at 9:18

1 Answer 1

1

A reasonable way to avoid the optional is an enum with associated values

For example

enum LoadingState {
    case idle, loading(Double), loaded(IotShadow), failed(Error)
}

@Published var state LoadingState = .idle

In the view switch on the state.

Sign up to request clarification or add additional context in comments.

2 Comments

This looks like a structurally nice solution, I will see if I can implement that in my project. Thanks!
The benefit is you can easily show different views depending on the state. The Double value of loading could be used for a progress bar. See also this article by John Sundell: swiftbysundell.com/articles/handling-loading-states-in-swiftui

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.