There seems to be some confusion on how to handle properties and local variables, you have for instance 1 property and 2 local variables named questionNumber
and you are also iterating the whole dictionary when as I see it you only want one question.
(在如何处理属性和局部变量方面似乎有些混乱,例如,您有1个属性和2个名为questionNumber
局部变量,并且您正在遍历整个字典,因为我看到它只想要一个问题。)
One way to get away from this and a solution that is also good for other reason like not doing everything in your controller class and separating responsibilities is to move the questions and handling of them into a separate struct or class.
(避免这种情况的解决方案以及因其他原因(例如,不执行控制器类中的所有工作并划分职责)而使解决方案也很好的一种方法是将问题移至单独的结构或类中。)
Let's create a Questions
struct that holds the questions, keeps track of what questions has been asked and can deliver the next question to ask.
(让我们创建一个包含Questions
结构,跟踪已提出的问题,并提供下一个要提出的问题。)
struct Questions {
private randomQuestions: [Int : String] = [
1: "Did you already agree to attend?",
2: "Does it cost money to attend?",
3: "Is it time consuming (4+ hours)?"
]
private var questionIndex = 0
mutating func nextQuestion() -> (number: Int, question: String?) {
questionIndex += 1
return (questionIndex, randomQuestions[questionIndex])
}
}
Note the question mark for the string in the return tuple, if no questions exists for a index (questionIndex > 3) the question returned will be nil
(注意返回元组中字符串的问号,如果索引不存在任何问题(questionIndex> 3),则返回的问题为nil)
Then you can use it in you code like this, first declare it as a property in your VC
(然后可以在这样的代码中使用它,首先在VC中将其声明为属性)
var questions = Questions()
Then when getting the question
(然后当收到问题时)
switch questionTypeReceived {
case "Random":
questionsImageView.image = UIImage(named: randomImages.randomElement()!)
let nextQuestion = question.nextQuestion()
if let question = nextQuestion.question {
questionTitleLabel.text = "Question #(nextQuestion.number)"
questionsTextLabel.text = question
} else {
// no more questions to ask, this needs to be handled
}
default: return
}
So a little more work to write a new struct but your code in the VC becomes simpler and a lot of properties and variables are no longer needed.
(因此,编写新结构需要更多的工作,但是VC中的代码变得更简单,并且不再需要许多属性和变量。)