SwiftUI:无法将类型为"Self"的值转换为预期的参数类型"绑定<C>"



我试图编写一个协议来为项目集合布局单元格视图,但出现了以下错误:

  • ⛔ Cannot convert value of type 'Self' to expected argument type 'Binding<C>'
import SwiftUI
// my protocol for laying out subviews
protocol Layout {

// associated types
associatedtype Item: Identifiable    // item data
associatedtype ItemView: View        // item view (cell)

// requirements
func cellSize(for item: Item) -> CGSize                 // cell size
func cellCenter(for item: Item) -> CGPoint              // cell position
@ViewBuilder func cellView(for item: Item) -> ItemView  // cell view for item
}
// an extension that I wish I could use the following syntax:
// `items.layoutCells(with: layout)`
extension RandomAccessCollection where Element: Identifiable
{
@ViewBuilder func layoutCells<L: Layout>(with layout: L) -> some View {
ForEach(self) { item in                     // ⛔ this is where the error occurs.
let size = layout.cellSize(for: item)
layout.cellView(for: item)
.frame(width: size.width, height: size.height)
.position(layout.cellCenter(for: item))
}
}
}

SwiftUI似乎正在尝试使用init<C>(_ data: Binding<C>, content: ...)初始化器来初始化我的ForEach实例,而不是使用我认为SwiftUI会使用的init(_ data: Data, content: ...)

我下一步该怎么做才能解决这个问题?谢谢

您忘记了关键约束在中间。

@ViewBuilder func layoutCells<L: Layout>(with layout: L) -> some View
where Element == L.Item {
ForEach(self) { item in

鉴于此,上述where Element: Identifiable可能是多余的。

最新更新