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

How would I return a View compliant to a protocol from SwiftUI View body?

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 resuling in:

enter image description 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

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

>Solution :

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
        }
    }
}
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