如何在Struct Swift中显示一个String

时间:2016-09-10 07:02:37

标签: ios iphone swift struct

我想在一个单独的函数中显示一个String,并在用户选择错误的答案时调用该函数,问题是当我创建该函数并尝试使用它时我的应用程序崩溃并告诉我一个错误索引超出范围.....任何建议如何解决这个问题?或建议做一个更好,更干净的工作?这是我的代码:

//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

    }
}

1 个答案:

答案 0 :(得分:1)

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

向您的班级添加媒体资源:

var questionInfo = ""

pickingRandomQuestion中设置值,然后调用removeAtIndex

questionInfo = questions[questionNumber].Info

然后使用showInformation中的属性值:

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