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):

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:

CustomView(view1: Text("Hi!"))

Currently I'm using like this:

CustomView(view1: Text("Hi!"), view2: Text(""), view3: : Text(""))

Hi @Renatafg ,
To solve your problem, you can explicitly pass the types of the arguments.

Like this:

CustomView<Text, EmptyView, EmptyView>(view1: Text("Hi!"))

If only the first view makes sense this is better:

CustomView<Text, Never, Never>(view1: Text("Hi!"))

Also:

extension CustomView where secondT == Never, thirdT == Never {
    init(view1: firstT) {
        self.view1 = view1
        view2 = nil
        view3 = nil
    }
}

PS

I'd prefer that firstT, secondT, and thirdT are upper camel case to follow the case convention.

2 Likes

That's what I was looking for! Thank you :star_struck:

Terms of Service

Privacy Policy

Cookie Policy