โ›”Cannot convert value of type 'Self' to expected argument type 'Binding<C>'

SwiftUI โŸฉ Layout โŸฉ Grids โŸฉ

๐Ÿ’Š ่งฃ่—ฅ๏ผš

@ViewBuilder func layoutCells<L: Layout>(with layout: L) -> some View
    where Element == L.Item    // ๐Ÿ’Š ่งฃ่—ฅ
{ ... }

๐Ÿ‘‰ StackOverflow

// 2022.02.17
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                     // โ›” error
            let size = layout.cellSize(for: item)
            layout.cellView(for: item)
                .frame(width: size.width, height: size.height)
                .position(layout.cellCenter(for: item))
        }
    }
}

Last updated