swift 编译器无法对此表达式进行类型检查?循环遍历数组以返回基于layoutType的项

b5lpy0ml  于 2023-03-16  发布在  Swift
关注(0)|答案(1)|浏览(213)

我想根据layoutType在不同的位置显示图像。
我是SwiftUI的新手,所以请告诉我,我有一个解决方案,在我心目中是有意义的,但我得到这个错误。The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
我已经做了我的公平份额谷歌的错误,它似乎是由许多不同的问题产生。错误出现在var: body some View
我先给你看我的结构体:

struct Mod: Identifiable {
    var id = UUID()
    var images: [String]
    var layoutType: Int
    
}

然后我的内容视图:

struct ContentView: View {
    
    var mods: [Mod] = [
        Mod(images: ["image1", "image2"], layoutType: 1),
        Mod(images: ["image3"], layoutType: 2),
        Mod(images: ["image4"], layoutType: 2),
        Mod(images: ["image5"], layoutType: 2),
        Mod(images: ["image6"], layoutType: 2)
    ]
    
    
    var body: some View {
        ZStack {
            Color.gray.ignoresSafeArea()
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(mods) { mod in
                        if mod.layoutType == 1 {
                            ForEach(mod.images, id: \.self) { item in
                                VStack {
                                    Image(item)
                                    }
                                }
                            }
                        }
                    }
                }
                .padding(.horizontal)
            }
        }
    }

任何帮助将不胜感激!

zy1mlcev

zy1mlcev1#

除了拼写错误mod.count之外,您确实需要将视图拆分为子视图。

struct ContentView: View {
    
    var mods: [Mod] = [
        Mod(images: ["image1", "image2"], layoutType: 1),
        Mod(images: ["image3"], layoutType: 2),
        Mod(images: ["image4"], layoutType: 2),
        Mod(images: ["image5"], layoutType: 2),
        Mod(images: ["image6"], layoutType: 2)
    ]
    
    
    var body: some View {
        ZStack {
            Color.gray.ignoresSafeArea()
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(mods) { mod in
                        if mod.layoutType == 1 {
                            SubView(mod: mod)
                        }
                    }
                }
            }
            .padding(.horizontal)
        }
    }
}

struct SubView: View {
    let mod : Mod
    
    var body: some View {
        ForEach(mod.images, id: \.self) { item in
            VStack {
                Image(item)
            }
        }
    }
}

相关问题