swiftPunk
swiftPunk

Reputation: 1

How can I define default empty input content for a function in SwiftUI?

I have a customContentViewFunction() that I like give an empty content like {} or EmptyView as default to it, which I do not have to do it in use case, for example I done same thing for color!

    struct ContentView: View {
    var body: some View {

        
        customContentViewFunction(content: Text("hello"), color: .green)
        
       // customContentViewFunction() : << Like this one!
        
    }
    
    
    func customContentViewFunction<Content: View>(content: Content, color: Color = Color.red) -> some View {

        ZStack {
            
            Rectangle()
                .fill(color)
 
             content

        }

    }
  
 
}

Upvotes: 0

Views: 276

Answers (1)

jnpdx
jnpdx

Reputation: 52387

Define another version/signature of the function where it gets passed EmptyView() for content.

You could either choose to define it with the color property still there, or leave that out and let it get set to the default in the original signature.

struct ContentView: View {
    var body: some View {
        customContentViewFunction()
    }
    
    func customContentViewFunction(color: Color = Color.red) -> some View {
        return customContentViewFunction(content: EmptyView(), color: color)
    }
    
    func customContentViewFunction<Content: View>(content: Content, color: Color = Color.red) -> some View {
        ZStack {
            Rectangle()
                .fill(color)
            content
        }
    }
}

Upvotes: 1

Related Questions