Home > database >  How to add a SwiftUI some View Type as a Requirement to an Protocol?
How to add a SwiftUI some View Type as a Requirement to an Protocol?

Time:09-16

Context

I have a Protocol and would like it to have a SwiftUI some View Type as one of its Requirements. I do know, that it is probably not the most elegant solution to mix the Model with the View, however, switching through all the different conforming Types each time I want to use the View isn't beautiful either. Even though, I ran into a problem while implementing and got the following Compiler Error:

'some' type cannot be the return type of a protocol requirement; did you mean to add an associated type?


Code

protocol Component {
    var row: some View { get } // -> Compiler Error thrown in this Line.
}

// There are actually many more Types conforming to Component.
enum ComponentA: Component {
    var row: some View { 
        Text("Component A")
    }
}

struct ComponentsView: View {
    var body: some View {
        ForEach(components) { component in
            component.row
        }
    }
}

Question

How can I achieve my goal of only having to define the selection of the appropriate SwiftUI View once?

CodePudding user response:

You could follow the same technique that Apple uses for View itself, which you can see by Command-clicking on a View reference in Xcode and selecting Jump to Definition.

protocol Component {
  associatedtype Body: View

  var row: Body { get }

As you declare some object's conformance to Component, the row autocomplete will automatically fill to some View:

Screenshot of autocomplete for the row method

  • Related