简体   繁体   中英

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

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?

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 :

行方法的自动完成屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM