0Day Forums
How to return a View type from a function in Swift UI - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: Swift (https://0day.red/Forum-Swift)
+--- Thread: How to return a View type from a function in Swift UI (/Thread-How-to-return-a-View-type-from-a-function-in-Swift-UI)



How to return a View type from a function in Swift UI - pudens783 - 07-19-2023

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.


RE: How to return a View type from a function in Swift UI - Sirjawaidoxhgclza - 07-19-2023

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.


RE: How to return a View type from a function in Swift UI - lanaebqctmcwadb - 07-19-2023

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

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

return AnyView(EmptyView())

}
```


RE: How to return a View type from a function in Swift UI - grislyx - 07-19-2023

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.


RE: How to return a View type from a function in Swift UI - norlands677162 - 07-19-2023

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]




RE: How to return a View type from a function in Swift UI - phono183361 - 07-19-2023

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