Provide a default implementation for a protocol method returning an associatedtype

61 Views Asked by At

I have this basic protocol:

protocol MyProtocol {
    associatedtype Content: View
    @MainActor @ViewBuilder func content() -> Content
}

I want to provide a default implementation for content(), so I figured I'd do this:

extension MyProtocol {
    @MainActor @ViewBuilder func content() -> some View {
        EmptyView()
    }
}

That works. However, now autocompletion in conforming types does something strange. Instead of making the return type some View, it uses Content, which does not compile:

struct Implementation: MyProtocol {
    func content() -> Content { // Auto-completed, does not compile
        Text("ABC")
    }
}

I have to manually fix the return type:

struct Implementation: MyProtocol {
    func content() -> some View { // Now it compiles
        Text("ABC")
    }
}

Is there a way to fix this behavior?

1

There are 1 best solutions below

0
AnderCover On

As stated in the comment section, the issue is that the associatedtype Content is not yet defined when you are trying to use autocompletion. If you define Content with a typealias before implementing the content() func autocompletion will behave as expected. ie:


struct Implementation: MyProtocol {
    typealias Content = Text
    
    func content() -> Text {
        <#code#>
    }
}