I've started to make a basic quiz game using Swift. I've written a struct to define what I want relating to each question:
struct Question {
let question: String
let answers: [String]
let correctAnswer: Int
}
The game will be a basic maths quiz, so will show random maths questions. I've written a function to randomise the questions and obtain the answers:
func questionAnswerBuilder() -> (question: String, answer: String) {
let first: Int = randomNumber()
let second: Int = randomNumber()
let arr = [first,second].sorted(by: >)
let firstAsString = String(arr[0])
let secondAsString = String(arr[1])
let questionString = "\(firstAsString) + \(secondAsString)"
let question = questionString
//Answer:
let answerString = first + second
let answer = String(answerString)
return (question, answer)
}
I have tested this in playgrounds and it works fine. Each time it creates a random number and outputs that along with the correct answer. Now I'd like to use this in each question...
var questionTest = questionAnswerBuilder()
var questions: [Question] = [
Question(question: questionTest.question, answers: [randomAnswer(), randomAnswer(), questionAnswerBuilder().answer, randomAnswer()], correctAnswer: 2),
Question(question: questionTest.question, answers: [randomAnswer(), randomAnswer(), questionAnswerBuilder().answer, randomAnswer()], correctAnswer: 2)
]
For info, the randomAnswer()
function is not displayed here. It's basically just a random number generator.
When I input all of this into Xcode I get the following message:
Cannot use instance member 'questionTest' within property initializer; property initializers run before 'self' is available
.
I currently have the questionAnswerBuilder()
function in its own swift file. I have tried moving this to the same file as my questions
variable but I still get the same fault. I have also tried making the questionTest
variable lazy but this makes no difference.
Please please please could someone point out where I am going wrong!
Thanks in advance!