Is there any way to assign a default value to a generic parameter in swift?

I define a struct of OptionClosureView.

struct OptionClosureView<Content: View>: View {
    var content: (()->Content)? = nil
    
    var body: some View {
        if content == nil{
            Text("Hello, World!")
        }else{
            content!()
        }
    }
}

If I don’t want to assign a value to the property of "content", I mean a default Text view for OptionClosureView. In this case, I just want to declare it as below:

OptionClosureView()

instead of:

OptionClosureView<Text>()

or

OptionClosureView<Image>()

or

….

IMO, I don’t care what is "Content" standing for in this case. Is there any way to assign a default value to the generic parameter "Content" in order to allow me to invoke OptionClosureView() directly? Something like:

struct OptionClosureView<Content: View = Text>: View {
....
}

>Solution :

You can add a convenience init that calls the default init with nil content and let the compiler infer the type by only making this init available for a single Content type using a generic where clause. The type can be any View type, I’ve just used EmptyView as an example.

extension OptionClosureView where Content == EmptyView {
  init() {
    self.init(content: nil)
  }
}

let noContentView = OptionClosureView() // the type of this is OptionClosureView<EmptyView>
let contentView = OptionClosureView { Text("Content") } // OptionClosureView<Text>

Leave a Reply