Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading