0

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

        }

    }
  
 
}

1 Answer 1

1

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Since we have no initializer for any functions at all I mean in general case of func, in this kind of situations should we always define multiple functions to get the flexibility?
Just looking at the heads for lots of Apple's Swift code, you can see there are often multiple signatures for functions for flexibility.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.