ios - 如何从 Struct Swift 中显示一个字符串

标签 ios iphone 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
}

关于ios - 如何从 Struct Swift 中显示一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423515/

相关文章:

ios - 自定义 UITableViewCell 不工作(drawRect :) on device [Swift]

ios - 如何在深色模式下单击按钮时使状态栏文本颜色变暗?

iphone - 如何在 xcode4.3 中获取和修改显示屏幕大小

ios - 如何等待结果异步代码

ios - 如果应用程序是使用 react-native 构建的,如何在 iOS 的 "Open in"对话框中注册应用程序?

iphone - 在 iPhone 中发布 URL 时,连接 didReceiveData 调用了两次?

ios - Swift:如何将 NSIndexPath 绑定(bind)到 addTarget

iOS - 相同的 .app 名称

Iphone sdk - 比较 NSNumber 时的奇怪行为

iphone - “Normal” UIButton 导致 obj_stack_overflow 或 EXC_BAD_ACCESS 异常