Evana
Evana

Reputation: 1794

Generic parameter 'Content' could not be inferred SwiftUI

I have a PersonView like following

struct PersonView<Content>: View where Content: View {

    let text: Text
    let detailText: Text
    var content: (() -> Content)? = nil

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            text
            detailText
            content?()
        }
    }
}

Also My sample model looks like:

struct Person {
    let name: String
    let age: Int
}

To make life easy I have made an extension of PersonView

extension PersonView {
    init<Content: View>(person: Person, content: (() -> Content)? = nil) {
        self.init(text: Text(person.name),
                  detailText: Text("\(person.age)"), content: content)
    }
}

but here I am getting error like "Cannot convert value of type '(() -> Content)?' to expected argument type 'Optional<(() -> _)>'"

I am not sure where I am getting wrong

Upvotes: 5

Views: 6554

Answers (1)

Sweeper
Sweeper

Reputation: 271355

You should not declare an extra generic parameter Content in the initialiser. The initialiser should not be generic, and instead just use the Content generic parameter from PersonView:

extension PersonView {
    init(person: Person, content: (() -> Content)? = nil) {
        self.init(text: Text(person.name),
                  detailText: Text("\(person.age)"), content: content)
    }
}

The extra Content that you declared is a different generic parameter from the Content in PersonView<Content>, which is why the compiler says it can't convert the types.

Upvotes: 2

Related Questions