Reputation: 1
I have this down function which I want the content carry a default value, I want this function get to work:
func viewFunction<Content: View>(content: Content = { Text("Hello!") }) -> some View {
return content
}
I know that I can split the function for this reason, but I want to have the function which carries the default value for content, also I do not want to have 2 functions.
my Goal: I want be able use my function in form of: viewFunction()
Update:
Swift doesn't have defaults for generic placeholders.
Upvotes: 0
Views: 863
Reputation: 16124
Use AnyView
and return EmptyView
. Example:
let shortcut: TabShortcut
var body: some View {
guard let url = URL(string: shortcut.link) else {
return AnyView(EmptyView())
}
let link = Link(destination: url) {
Text("\(shortcut.title)")
}
return AnyView(link)
}
Upvotes: 0
Reputation: 1
The most possible way is having 2 function's. Like down codes:
PS: We cannot have the function which carries the default value for a generic type.
struct ContentView: View {
var body: some View {
viewFunction(content: Text("Hello, world!"))
viewFunction()
}
}
func viewFunction<Content: View>(content: Content) -> some View {
return content
}
func viewFunction() -> some View {
return Text("Hello, world!")
}
Upvotes: 1
Reputation:
I like the answer with as!
-casting because it will preserve documentation without code generation.
But the general solution is to overload, because Swift doesn't have defaults for generic placeholders.
Note: this question is not SwiftUI-specific.
func viewFunction<Content: View>(content: Content) -> some View { content }
func viewFunction() -> some View {
viewFunction(content: Text("Hello!"))
}
Upvotes: 0
Reputation: 179
Simply with:
func viewFunction<Content: View>(content: () -> Content = { Text("hello") as! Content }) -> some View {
return content()
}
Upvotes: 3