swiftPunk
swiftPunk

Reputation: 1

How can gave a View as default value in a View Function in SwiftUI?

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

Answers (4)

Denis Kutlubaev
Denis Kutlubaev

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

swiftPunk
swiftPunk

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

user652038
user652038

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

user3124975
user3124975

Reputation: 179

Simply with:

func viewFunction<Content: View>(content: () -> Content = { Text("hello") as! Content }) -> some View {
  return content()
}

Upvotes: 3

Related Questions