Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 885 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to return a View type from a function in Swift UI

#1
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.
Reply

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

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

The final solution will look like this:

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

I think this is the most concise solution.
Reply

#3
Making AnyView() wrapper
```
func getView(view: String?) -> AnyView {

if view == "CreateUser" {
return AnyView(CreateNewsView())
}

return AnyView(EmptyView())

}
```
Reply

#4
As of Swift 5.3 @hồng-phúc Answer is somehow right, just needs adding the @ViewBuilder Property explicitly.

```swift
@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.
Reply

#5
You should return `some View`

EX:

func getView(view: String) -> some View {
return YourView()
}
for more detail a bout some View, view [this][1]


[1]:

[To see links please register here]

Reply

#6
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())
}
}
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through