簡體   English   中英

返回在 swift 協議 function 中查看相關類型

[英]return View in swift protocol function with associatedtype

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")
  }
}

我正在嘗試在這里創建一個可重用的協議。 我收到錯誤,這些錯誤在此處添加為評論。 在網上找不到任何解決方案來解決這個問題。 我怎樣才能使這段代碼工作? 或者有什么建議可以在哪里查找有關它的更多信息? 謝謝!

具有關聯類型的協議不能用作類型(但是在 Swift 5.7 中可以)

由於錯誤狀態,您必須使用受協議約束的 generics

例如

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")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM