Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a View type from a function in Swift UI

Tags:

ios

swift

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.

like image 615
James Avatar asked Jul 14 '20 13:07

James


People also ask

Can a function return a view SwiftUI?

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.

How does a function return a value in Swift?

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.


2 Answers

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())
        }
    }
like image 43
James Avatar answered Nov 12 '22 19:11

James


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.

like image 107
Frederik Winkelsdorf Avatar answered Nov 12 '22 18:11

Frederik Winkelsdorf