请帮助我,因为我是一个初学者在SwiftUI和编程整体.这是我第一次开发一个琐事应用程序.我遇到了一个问题与 Shuffle 的答案琐事问题.我试图创建一个函数,包含所有的答案,包括正确的一个,并随机 Shuffle 他们,但我真的不知道如何做到这一点.请帮助我,任何一点帮助是非常感谢.
这是我的TriviaAPIData代码:
import Foundation
struct QuestionResponse: Decodable {
var results: [Question]
}
struct Answer: Identifiable {
var id = UUID()
var text: String
var isCorrect: Bool
}
struct Question: Decodable {
var category: String
var question: String
var correctAnswer: String
var incorrectAnswers: [String]
}
字符串
这是我的TriviaAPI代码:
import Foundation
import SwiftUI
class TriviaAPI: ObservableObject {
struct TriviaAnswer {
let text: String
let isCorrect: Bool
}
@Published var QnAData: [Question] = []
func getQnAData(selectedCategoryNumber: Int, selectedDifficultyInPopup: String) async throws {
let endpoint = "https://opentdb.com/api.php?amount=10&category=\(selectedCategoryNumber)&difficulty=\(selectedDifficultyInPopup)&type=multiple&encode=url3986"
guard let url = URL(string: endpoint) else {throw APIErrors.invalidURL}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let (data, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
throw APIErrors.invalidResponse
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let questionResponse = try decoder.decode(QuestionResponse.self, from: data)
DispatchQueue.main.sync {
self.QnAData = questionResponse.results
}
} catch {
throw APIErrors.invalidData
}
}
}
型
下面是我的QuizGameScreen代码:
import Foundation
import SwiftUI
struct QuizGameScreen: View {
@StateObject var api = TriviaAPI()
@Binding var selectedCategoryNumber: Int
@Binding var selectedCategoryName: String
@State var currentQuestionIndex = 0
@Binding var selectedDifficultyInPopup: String
func shuffleAnswers() {
var correctAnswers = [api.QnAData[currentQuestionIndex].correctAnswer]
var incorrectAnswers = api.QnAData[currentQuestionIndex].incorrectAnswers
let allAnswers = correctAnswers + incorrectAnswers
var shuffeldQuestions = allAnswers.shuffled()
}
var body: some View {
ZStack{
Image("NewBgQuizUp")
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight:.infinity)
VStack(alignment: .leading){
Text("QuizUp")
.font(.system(size: 36, design:
.rounded)).fontWeight(.bold)
.foregroundColor(.white)
.offset(x: -100, y: -350)
}
Text("1 out of 0")
.font(.system(size: 23, design:
.rounded)).fontWeight(.bold)
.foregroundColor(.white)
.offset(x: 100, y: -300)
VStack{
if !api.QnAData.isEmpty {
if currentQuestionIndex < api.QnAData.count { // Check if the current question index is within bounds
if let decodedQuestion = api.QnAData[currentQuestionIndex].question.removingPercentEncoding {
Text(decodedQuestion)
.font(.system(size: 23, design: .rounded)).fontWeight(.bold)
.foregroundColor(.white)
.offset(y: -100)
} else {
Text("Failed to decode question")
.font(.system(size: 23, design: .rounded)).fontWeight(.bold)
.foregroundColor(.white)
.offset(y: -100)
}
ForEach(0..<api.QnAData[currentQuestionIndex].incorrectAnswers.count, id: \.self) { index in
if index < api.QnAData[currentQuestionIndex].incorrectAnswers.count { // Check if the index is within bounds
if let decodedAnswer = api.QnAData[currentQuestionIndex].incorrectAnswers[index].removingPercentEncoding {
Button(action: {
print("wrong answer")
}) {
Text(decodedAnswer)
.font(.system(size: 20, design: .rounded))
.foregroundColor(.purple)
.frame(width: 300, alignment: .leading)
.padding()
.background(Color.white)
.fontWeight(.bold)
.cornerRadius(10)
}
}
}
}
if currentQuestionIndex < api.QnAData.count {
if let decodedCorrectAnswer = api.QnAData[currentQuestionIndex].correctAnswer.removingPercentEncoding {
Button(action: {
print("correct answer")
}) {
Text(decodedCorrectAnswer)
.font(.system(size: 20, design: .rounded))
.foregroundColor(.purple)
.frame(width: 300, alignment: .leading)
.padding()
.background(Color.white)
.fontWeight(.bold)
.cornerRadius(10)
}
}
}
}
} else {
Text("Loading...")
.font(.system(size: 23, design: .rounded)).fontWeight(.bold)
.foregroundColor(.white)
.offset(y: -100)
}
}
}.task {
do {
try await api.getQnAData(selectedCategoryNumber: selectedCategoryNumber, selectedDifficultyInPopup: selectedDifficultyInPopup)
shuffleAnswers() // calling on my function
} catch APIErrors.invalidData {
print("Invalid Data")
} catch APIErrors.invalidURL {
print("Invalid Url")
} catch APIErrors.invalidResponse {
print("Invalid Response")
} catch {
print("General error")
}
}
}
}
struct QuizGameScreen_Previews: PreviewProvider {
static var previews: some View {
QuizGameScreen(selectedCategoryNumber: .constant(21), selectedCategoryName: .constant("Sport"), selectedDifficultyInPopup: .constant("Easy"))
}
}
enum APIErrors: Error {
case invalidURL
case invalidResponse
case invalidData
}
型
1条答案
按热度按时间rsl1atfo1#
如果你想拥有一个包含
correctAnswer
的混洗答案数组,那么你可以使用:用途:字符串
这将给你给予(返回)一个可以在代码中使用的随机答案数组。
注意,你没有显示你想在代码中使用它的地方。
还要注意的是,尽管测试了边界,但在
QuizGameScreen
中使用索引并不是一个好主意,特别是在ForEach
循环中。