如何为结构的每个成员分配一个编号? (swift)

How do I assign a number to each member of a structure? (swift)

我有一个测验应用程序。我希望用户能够按 "Next Question" 按钮并能够按顺序访问问题 1、问题 2、问题 3 等。

我希望该应用程序有一个后退按钮,以便用户也可以访问之前的问题。例如,如果用户正在回答问题 3,则他们可以按后退按钮并访问问题 2。

我正在考虑为问题结构中的每个问题分配一个编号,因此根据按下的按钮调用下一个编号问题或上一个编号问题,即 "Next Question" 按钮或 "Previous Question" 按钮。

这是我设置问题的方式:

struct  Question {
    var Question : String!
    var Answers : String!
}

var Questions = [Question]()
var QNumber = Int() 


@IBOutlet weak var labelForQuestion: UILabel!
@IBOutlet weak var textBoxForAnswer: UITextView!



override func viewDidLoad() {    
    //hiding answer
    textBoxForAnswer.hidden = true

    //Load Questions
    Questions = [

        Question(Question: "This is question 1", Answers: "This is answer 1"),

        Question(Question: "This is question 2", Answers: "This is answer 2"),

        Question(Question: "This is question 1", Answers: "This is answer 1"),

    ]
    pickQuestion()
}


func pickQuestion() {

    if Questions.count > 0 {

        //setting Qnumber equal to 0 gives sequential quiz game no repeats
        QNumber = 0

        labelForQuestion.text = Questions[QNumber].Question
        textBoxForAnswer.text = Questions[QNumber].Answers

        //remove question so it doesnt come up again
        Questions.removeAtIndex(QNumber)
    }
}


@IBAction func Next(sender: AnyObject) {
    pickQuestion()
}


@IBAction func showAnswer(sender: AnyObject) {
    textBoxForAnswer.hidden = false
}

所以基本上我想制作 UIActions 这将使我能够在问题之间来回切换。关于我将如何做到这一点的任何想法?

您应该从 pickQuestion 中删除 QNumber = 0 并在外部递增/递减它。此外,您可能应该删除 Questions.removeAtIndex(QNumber)。总的来说,变化应该是:

指定初始 QNumber

var QNumber : Int = 0

更改 pickQuestion 逻辑:

func pickQuestion() {
    labelForQuestion.text = Questions[QNumber].Question
    textBoxForAnswer.text = Questions[QNumber].Answers
}

更改 Next:

@IBAction func Next(sender: AnyObject) {
    QNumber++; // you need some handling to not go out of bounds if you are already showing the last question
    pickQuestion()
}

同样适用于 previous(...)QNumber--

补充说明:

  • 请让方法和变量以小写字母开头:nextqNumberquestions、每个成员question