简体   繁体   中英

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

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.

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.

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

Making AnyView() wrapper

func getView(view: String?) -> AnyView {
     
   if view == "CreateUser" {
       return AnyView(CreateNewsView())
   }
    
   return AnyView(EmptyView())
        
}

You should return some View

EX:

func getView(view: String) -> some View {
     return YourView()
}

for more detail a bout some View, view this

I use the extension .eraseToAnyView () to make func with some View easier:

extension View {
      public function eraseToAnyView () -> AnyView {
          AnyView (on its own)
      }
}

The final solution will look like this:

func getView (view: String?) -> AnyView {
         if view == "CreateUser" {
         return CreateNewsView().eraseToAnyView()
     }
         return EmptyView().eraseToAnyView()
}

I think this is the most concise solution.

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