从3个数组中获取值,以便在ForEach中使用



我有三个数组,我想从所有数组中抓取并显示给用户。当我有两个数组时,我在下面找到了这个代码,它工作得很好

List(Array(zip(book.words, book.definitions)), id: .self.0) { (word, definition) in
HStack {
Text("(word) - (definition)")
Spacer()
Button(action: {
textToSpeech(word)
}) {
Image(systemName: "speaker.3")
}.buttonStyle(PlainButtonStyle())
}
}

但是,我不能向它添加另一个数组,因为这是不允许的。我试图以数组中的计数为基础,因为它们的大小都相同。

List {
ForEach(0 ..< book.words.count, id: .self) { index in
HStack {
Text("(book.words[index]) ((book.partOfSpeech[index])) - (book.definitions[index])")
Spacer()
Button(action: {
//                        print("hello")
textToSpeech(book.words[index])
}) {
Image(systemName: "speaker.3")
}.buttonStyle(PlainButtonStyle())
}
}
}

然而,我得到这个错误

Swift/ContiguousArrayBuffer.swift:580: Fatal error: Index out of range
2021-07-19 19:43:31.572442-0700 SQLBook[61246:3585835] Swift/ContiguousArrayBuffer.swift:580: Fatal error: Index out of range

变量book是一个类,它被传入并用@ObservedObject进行装饰。我不确定我想做的事情是否可行,因为我见过有人问这个问题,但从未得到回应。

无论何时处理数组,最好检查要使用的索引是否存在。我怀疑你们三个阵列的大小不一样。我通过以下测试成功测试了您的代码:

import SwiftUI
@main
struct TestApp: App {
@StateObject var book = BookModel()
var body: some Scene {
WindowGroup {
ContentView(book: book)
}
}
}
class BookModel: ObservableObject {
@Published var words = ["word1","word2","word3"]
@Published var partOfSpeech = ["pos1","pos2","pos3"]
@Published var definitions = ["def1","def2","def3"]
}
struct ContentView: View {
@ObservedObject var book: BookModel

var body: some View {
VStack(alignment: .leading ){
if (book.words.count == book.partOfSpeech.count && book.words.count == book.definitions.count) {
List {
ForEach(book.words.indices, id: .self) { index in
HStack {
Text("(book.words[index]) ((book.partOfSpeech[index])) - (book.definitions[index])")
Spacer()
Button(action: {
textToSpeech(book.words[index])
}) {
Image(systemName: "speaker.3")
}.buttonStyle(PlainButtonStyle())
}
}
}
} else {
Text("arrays not the same size") // show somehting else
}
}
}

func textToSpeech(_ word: String) {
print("---> in textToSpeech word: " + word)
}
}

最新更新