同时迭代列表中的两个数组

问题描述 投票:0回答:1

如何迭代列表中的两个数组:

struct ContentView: View {
    let colors = ["red", "green", "blue"]        
    let names = ["John", "Apple", "Seed"] 

    var body: some View {           
        VStack {
            List(colors, id: \.self) { color in
                Text(color)
            }
        }
    }
}

例如,我需要具备:Text("\(color) - \(animal)")

我的代码将是这样(我知道这是错误的,但这就是这个主意):

    List(colors, animals id: \.self) { color, animal in
        Text("\(color) - \(animal)")
    }
swiftui swiftui-list
1个回答
0
投票

您应该像这样使用元组:

let objects = [("red", "John"), ("green", "Apple"), ("blue", "Seed")]

然后,您可以执行以下操作:

List(objects, id: \.self) { object in
    Text("\(object.0) - \(object.1)")
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.