Home > Back-end >  How would I return a View conforming to a protocol from SwiftUI View body?
How would I return a View conforming to a protocol from SwiftUI View body?

Time:10-24

I've tried this

protocol ErrorableViewProtocol: View {
    var error: Error? { get set }
}

struct ErrorableView: View {
    var normal: any ErrorableViewProtocol
    var error: Error
    
    var body: some View {
        if let error = normal.error {
            ErrorView(error: error)
        } else {
            normal
        }
    }
}

but my knowledge of swift is lacking resulting in:

enter image description here

Please advice what's a good way to show an ErrorView in place or navigate to that once a network error has happened. Thanks.

CodePudding user response:

You would need to make your View generic:

struct ErrorableView<T: ErrorableViewProtocol>: View {
    var normal: T
    var error: Error
    
    var body: some View {
        if let error = normal.error {
            ErrorView(error: error)
        } else {
            normal
        }
    }
}
  • Related