简体   繁体   中英

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.

Thanks, Marcus

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM