Is it possible to have an optional generic inference that obeys the View protocol?

Hi! I have a custom struct that have 3 optional generic views (so I can use as Text, Navigation Item, Button or anything):
Code Block
struct CustomView<FirstT: View, SecondT: View, ThirdT: View>: View {
var view1: FirstT?
var view2: SecondT?
var view3: ThirdT?
var body: some View { ... }
}

So, my the problem is when I am going to use it. Swift can't infer the type of the views, even when the are nil. How can I solve this problem?

I need this to use my init like this:
Code Block
CustomView(view1: Text("Hi!"))

Currently I'm using like this:
Code Block
CustomView(view1: Text("Hi!"), view2: Text(""), view3: : Text(""))

or
Code Block
CustomView<Text, Text, Text>(view1: Text("Hi!"))



Accepted Reply

In Swift, nil is a context-dependent literal representing Optional<Wrapped>.none and Swift needs to infer the Wrapped type.

As a workaround, you can define type-constrained initializers.
Code Block
extension CustomView where SecondT == EmptyView, ThirdT == EmptyView {
    init(view1: FirstT?)  {
        self.view1 = view1
        self.view2 = nil
        self.view3 = nil
    }
}
extension CustomView where ThirdT == EmptyView {
    init(view1: FirstT?, view2: SecondT?)  {
        self.view1 = view1
        self.view2 = view2
        self.view3 = nil
    }
}


Replies

In Swift, nil is a context-dependent literal representing Optional<Wrapped>.none and Swift needs to infer the Wrapped type.

As a workaround, you can define type-constrained initializers.
Code Block
extension CustomView where SecondT == EmptyView, ThirdT == EmptyView {
    init(view1: FirstT?)  {
        self.view1 = view1
        self.view2 = nil
        self.view3 = nil
    }
}
extension CustomView where ThirdT == EmptyView {
    init(view1: FirstT?, view2: SecondT?)  {
        self.view1 = view1
        self.view2 = view2
        self.view3 = nil
    }
}