gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:34:31 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com