如何从Swift的Struct中显示字符串



我想在一个单独的函数中显示一个字符串,当用户选择错误的答案时只是调用函数,问题是当我创建函数时,我尝试使用它,我的应用程序崩溃,并告诉我一个关于索引超出范围.....的错误有什么建议我怎么解决这个问题吗?还是建议你把工作做得更好、更干净?下面是我的代码:

//This is my struct
struct Question {
var Question: String!
var Answers: [String]!
var Answer: Int!
var Img: UIImage!
var Info: String!
} 
override func viewDidLoad() {
    super.viewDidLoad()
//Here the way I display the questions
questions = [
        Question(
            Question: "Question #1",
            Answers: ["A","B","C","D"],
            Answer: 1,
            Img: UIImage.self(named: "steve"),
            Info: "Steve"
                ),
]
//Here is my function that I want to create to display the Info:
private function showInformation() {
infoLabel.text = questions[Question].Info
}

Ps:如果需要更多的细节让我知道,顺便说一下,我的功能是创建一个随机问题是这个

private func pickingRandomQuestion() {
    if questions.count > 0  {
        questionNumber = random() % questions.count //This make a random pick of Question
        questionLabel.text = questions[questionNumber].Question //Converting quesitonLabel into TEXT
        answerNumber = questions[questionNumber].Answer
        imgDisplay.image = questions[questionNumber].Img
//Im trying to use one of this examples to display but is not working :(
        answerA.setTitle(questions[questionNumber].Answers[0], forState: .Normal)
        answerB.setTitle(questions[questionNumber].Answers[1], forState: .Normal)
        answerC.setTitle(questions[questionNumber].Answers[2], forState: .Normal)
        answerD.setTitle(questions[questionNumber].Answers[3], forState: .Normal)
        questions.removeAtIndex(questionNumber)
    } else {
        finishGame.hidden = false
        answerA.hidden = true
        answerB.hidden = true
        answerC.hidden = true
        answerD.hidden = true
    }
}

在从问题数组中删除问题之前,需要将问题的信息存储在属性中。

为你的类添加一个属性:

var questionInfo = ""

pickingRandomQuestion中,设置调用removeAtIndex前的值:

questionInfo = questions[questionNumber].Info

则使用showInformation中的属性值:

private function showInformation() {
    infoLabel.text = questionInfo
}

最新更新