I am trying to create a somewhat elegant navigation system for my App. Below is a function that attempts to return a View type. This does not compile with:
func getView(view: String) -> View {
switch view {
case "CreateUser":
return CreateNewsView()
default:
return nil
}
}
The above results in a compile error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
Thank you for your help.
The body property of any SwiftUI automatically gets the ability to return different views thanks to a special attributed called @ViewBuilder . This is implemented using Swift's result builder system, and it understands how to present two different views depending on our app's state.
If you want to return your own value from a function, you need to do two things: Write an arrow then a data type before your function's opening brace, which tells Swift what kind of data will get sent back. Use the return keyword to send back your data.
I managed to fix this by using the AnyView() wrapper:
func getView(view: String?) -> AnyView {
switch view {
case "CreateUser":
return AnyView(CreateNewsView())
default:
return AnyView(EmptyView())
}
}
As of Swift 5.3 @hồng-phúc Answer is somehow right, just needs adding the @ViewBuilder Property explicitly.
@ViewBuilder func getView(view: String) -> some View {
switch view {
case "CreateUser":
Text(view)
case "Abc":
Image("Abc")
default:
EmptyView()
}
}
Side note: Please avoid using String Literals. Better use an enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With