XcodeでswiftUIを使って写真の4択クイズを作ろうとしているのですが、下の星で挟まれている部分のコードで、
Thread 1: Fatal error: Index out of range
というエラーが出てしまいます。
配列の要素も四つ以上あるので問題ない気がして、自分ではわかりかねているので、わかる方いたら教えていただきたいです。
よろしくお願いします。
下が、問題のコードです。
import SwiftUI
struct ContentView: View {
let imageFileNames = ["CorrectImage1", "CorrectImage2", "CorrectImage3", "CorrectImage4", "WrongImage1", "WrongImage2", "WrongImage3", "WrongImage4"]
@State private var gameCount = 0 @State private var correctImageFileName = "" @State private var chosenImageFileNames: [String] = [] @State private var showingAlert = false @State private var alertTitle = "" var body: some View { VStack { if gameCount < 20 { VStack { ForEach(0..<2) { rowIndex in HStack { ForEach(0..<2) { columnIndex in ☆☆☆☆ let chosenImage = chosenImageFileNames[rowIndex * 2 + columnIndex] ☆☆☆☆ Button(action: { if chosenImage == correctImageFileName { alertTitle = "正解!" gameCount += 1 } else { alertTitle = "間違い!" } showingAlert = true }) { Image(chosenImage) .resizable() .frame(width: 100, height: 100) } .padding(20) } } .frame(maxWidth: .infinity) } } .alert(isPresented: $showingAlert) { Alert(title: Text(alertTitle), dismissButton: .default(Text("OK")) { if gameCount < 20 { selectImages() } }) } } else { Text("終了!") } } .onAppear { selectImages() } } func selectImages() { var chosenIndices = [Int]() let correctIndex = Int.random(in: 0..<imageFileNames.count) chosenIndices.append(correctIndex) correctImageFileName = imageFileNames[correctIndex] while chosenIndices.count < 4 { let randomIndex = Int.random(in: 0..<imageFileNames.count) if !chosenIndices.contains(randomIndex) { chosenIndices.append(randomIndex) } } chosenImageFileNames = chosenIndices.map { imageFileNames[$0] } }
}

下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。