我需要在randomQuestionGenerator函数之外使用currentQuestion变量。什么是事先声明它的正确语法?
var abc = function(val = 123) {
return {
log : function() {
console.log(this.val);
},
val
};
}
var def = abc(); // optionally pass parameters to `abc()` call
def.log();
答案 0 :(得分:1)
您可以在函数外声明currentQuestion
作为可选项:
var currentQuestion : Questions? = nil
func RandomQuestionGenerator() {
let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count)))
currentQuestion = fullQuestions[randomQuestion]
correctAnswer = currentQuestion.answer
}
虽然你可以这样做,但更好的方法是让你的函数返回随机问题,如下所示:
func RandomQuestionGenerator() -> Questions {
let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count)))
return fullQuestions[randomQuestion]
}
现在您可以使用该函数检索下一个随机问题,并根据需要获取其字段:
let nextQuestion = RandomQuestionGenerator()
print(nextQuestion.Question)
print(nextQuestion.answers)