When using SwiftUI, I like to create functions that return Views, it's just an easy way to separate and clean up the code. Like this:
func deleteButton() -> some View { return (Button...) }
This works like a charm, but when I try to return a List like this:
func itemsList() -> List<Never, some DynamicViewContent> { ... }
I get the error "'some' types are only implemented for the declared type of properties and subscripts and the return type of functions". I tried it without "some", and just "DynamicViewContent" without List, but neither has worked.
Can someone help me with this?
CodePudding user response:
Option #1:
Return some View
:
func myList() -> some View {
List(items, id:\.self) { item in
Text("Hello")
}
}
Option #2:
Use the specific type. The easiest way I can think of to get this is to temporarily set a variable to the List
. For example:
var myList = List(items, id:\.self) { item in
Text("Hello")
}
If I then Option-Click on myList
, Xcode will display a popup showing the exact type that myList
is inferred to be. You can use that as the return type for your function. In the case of my contrived example, it is List<Never, ForEach<[GameModel], GameModel, Text>>
where items
is [GameModel]
CodePudding user response:
You can specify a generic parameter instead:
func itemsList<Content: DynamicViewContent>() -> List<Never, Content> { }