我在Swift中構建遊戲來評估選擇A與選擇B相比是否爲真。遊戲對於字符串正常工作,但我想顯示圖像而不是字符串(例如對於firstQuestion.choiceA = "A"
,不顯示「A」而是顯示與A相關的圖像 - 對於B是相同的)。我已經看到字典的解決方案將字符串映射到圖像或提取和比較圖像名稱,但不知道如何實現在我的情況。代碼的主要部分是封閉的。有人有這樣的例子在Swift中如何做到這一點?真假遊戲中的顯示圖像選擇
import UIKit
class ViewController: UIViewController {
class Questions {
var question : String
var answer : String
var choiceA : String
var choiceB : String
init() {
question = ""
answer = ""
choiceA = ""
choiceB = ""
}
func isCorrect(input : String) -> Bool {
return input == answer
} }
class QuestionGenerator {
var questionList : [Questions]
var counter : Int
var currentQuestion : Questions/
init() {
questionList = [Questions]()
counter = 0
currentQuestion = Questions()
}
func addQuestion(question : Questions) {
questionList.append(question)
}
func getNextQuestion() -> Questions {
if (counter < questionList.count) {
currentQuestion = questionList[counter]
counter = counter + 1
return currentQuestion
}
else
{
counter = 0
currentQuestion = questionList[counter]
return currentQuestion
} } }
class Model
{
var currentQuestion : Questions
var questionGen : QuestionGenerator
init()
{
let firstQuestion = Questions()
firstQuestion.question = "Which one took longer?"
firstQuestion.choiceA = "A"
firstQuestion.choiceB = "B"
firstQuestion.answer = firstQuestion.choiceA
questionGen = QuestionGenerator()
questionGen.addQuestion(firstQuestion)
}
func isCorrect(userInput : String) -> Bool
{
return userInput == currentQuestion.answer
} }