Home > Mobile >  Initialization of a nested struct in SwiftUI
Initialization of a nested struct in SwiftUI

Time:12-31

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

CodePudding user response:

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.

  • Related