SwiftUI 编译时好时不好的错误之一

861 阅读1分钟

错误提示: The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

编译时好时不好的原代码:

ForEach(viewModel.lists[index], id: \.self) { item in
    if let ship = item {
        ownShipPalletCell(ship: ship) {
            navigationManager.wrappedValue.pushView(tag: "RootPage") {
                ShipPalletDetailPage(ship: ship, fromOwn: true)
            }
        } share: {

        }

    }
}

修改后编译成功的代码:

let list: [ShipPallet?] = viewModel.lists[index]
    ForEach(list, id: \.?.id) { item in
        if let ship = item {
            ownShipPalletCell(ship: ship) {
                navigationManager.wrappedValue.pushView(tag: "RootPage") {
                    ShipPalletDetailPage(ship: ship, fromOwn: true)
                }
            } share: {

            }

        }
    }

分析:应该是foreach 有时候不知道数据源问题,需要明确告诉编译器数据源和类型以及KeyPath<Data.Element, ID>