Home > Enterprise >  return View in swift protocol function with associatedtype
return View in swift protocol function with associatedtype

Time:08-24

public protocol NodeBuilder {
  associatedtype OutputView: View
  func build() -> OutputView
}

public struct Builder {
  private let builder: NodeBuilder // Protocol 'NodeBuilder' can only be used as a generic constraint because it has Self or associated type requirements
  
  public init(builder: NodeBuilder) { // Protocol 'NodeBuilder' can only be used as a generic constraint because it has Self or associated type requirements
    self.builder = builder
  }
  
  public func build<OutputView: View>() -> OutputView {
    builder.build() // Member 'build' cannot be used on value of protocol type 'NodeBuilder'; use a generic constraint instead
  }
}

struct Component: NodeBuilder {
  func build() -> some View {
    Text("Some View")
  }
}

I'm trying to create a reusable protocol here. I'm getting errors which are added as comments here. Can't find any solution online to solve this. How can I make this code work? Or any suggestions where to look up more info about it? Thanx!

CodePudding user response:

A protocol with associated types can not be used as a type (however in Swift 5.7 it can)

As the error states you have to use generics constrained to the protocol

For example

public protocol NodeBuilder {
    associatedtype OutputView: View
    func build() -> OutputView
}

public struct Builder<N: NodeBuilder>  {
    private let builder: N
    
    public init(builder: N) {
        self.builder = builder
    }
    
    public func build<N>() -> N {
        builder.build() as! N
    }
}

struct Component: NodeBuilder {
    func build() -> some View {
        Text("Some View")
    }
}
  • Related