Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialization of a nested struct in SwiftUI

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks,
Marcus

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading