将数组转换为对象

Converting Array into Object

我有一个组织如下的列表:["ImageUrl","Year","Credit","ImageUrl","Year","Credit"...] 我想显示水平滚动视图下面带有 year/credit 的图像。我试过像这样在 SwiftUI 中使用 while 循环,但我收到一条错误消息,指出包含控制流语句的 Closure 不能与函数构建器一起使用 'ViewBuilder'.

这是我的代码:

struct ImageList : View {
    
    var listOfImages : Array<String>
    @State var i = 0
    
    var body: some View{
        VStack{
        while i < listOfImages.count {
            VStack(){
                KFImage(listOfImages[i]).resizable().frame(width: 200, height: 300).aspectRatio(contentMode: .fit)
                Text(listOfImages[i+1])
                Text(listOfImages[i+2])
                }
            i = i+3
            }
        }
    }
}

我无法更新列表的组织方式,因为它已经来自我们的后端。我最初的计划是将列表元素导入到对象列表中,如下所示:

struct HistoricalImages: Hashable {
    let link : String
    let year : String
    let credit : String    
}

但我不确定如何有效地转换它。任何帮助表示赞赏。这是我的第一个 Whosebug post 所以如果需要添加任何内容请告诉我!

使用索引范围将数组切片为 3 个元素的组,并为每个切片创建一个对象

var index = 0
var items = [HistoricalImages]()
while index < array.count {
    let end = index + 2
    if end > array.count {
        break
    }

    let slice = Array(array[index...end])
    items.append(HistoricalImages(link: slice[0], year: slice[1], credit: slice[2]))
    index += 3
}

您不能在 body 属性:

中使用 while 循环
while i < listOfImages.count {
...
}

您需要使用 ForEach 来代替:

ForEach(0..<listOfImages.count) { idx in
...
}