1

I need to use the currentQuestion variable outside of the randomQuestionGenerator function. Whats the proper syntax for declaring it beforehand?

struct Questions {
    var Question: String
    var answer: Int
    var answers: [String]
}

class GameScreen: UIViewController {

var correctAnswer = 0
var fullQuestions: [Questions] = []

func RandomQuestionGenerator(){
    let randomQuestion = 
Int(arc4random_uniform(UInt32(fullQuestions.count)))
    var currentQuestion = fullQuestions[randomQuestion]
    correctAnswer = currentQuestion.answer
1
  • Why don't you make your currentQuestion similar to correctAnswer? Commented Aug 15, 2017 at 2:14

1 Answer 1

1

You can declare currentQuestion as an optional outside the function:

var currentQuestion : Questions? = nil
func RandomQuestionGenerator() {
    let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count)))
    currentQuestion = fullQuestions[randomQuestion]
    correctAnswer = currentQuestion.answer
}

Although you could do that, a better approach is to make your function return the random question, like this:

func RandomQuestionGenerator() -> Questions {
    let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count)))
    return fullQuestions[randomQuestion]
}

Now you can use the function to retrieve the next random question, and get its fields as needed:

let nextQuestion = RandomQuestionGenerator()
print(nextQuestion.Question)
print(nextQuestion.answers)
Sign up to request clarification or add additional context in comments.

3 Comments

The function has a lot more to it aside from just setting up a random question variable, I cut it out to keep it simple.
Also when I try to declare it as type of questions, my view controller says it has no initializers and doesn't run, why is this?
@RichardParker It needs to be optional, too, so that an unassigned state would be allowed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.