popetec popetec - 7 months ago 26
Swift Question

Array Index out of range on using button

Beginner here, first Swift app. I can't seem to prevent my array from going out of range when pushing the

nextPage
button.

My code:

class ViewController: UIViewController {

var score: Float = 0.0
var questions: [Question] = []
var index = 0


@IBAction func nextPage(sender: AnyObject) {

if questions.count < 9 {
savesliderValues()
incrementIndex()
loadQuestions()
calculatetotalScore()
} else {
savesliderValues()
}
}


@IBOutlet weak var backbuttonOutlet: UIBarButtonItem!
@IBAction func backButton(sender: AnyObject) {
savesliderValues()
decrementIndex()
loadQuestions()
}

@IBOutlet weak var question1Label: UILabel!
@IBOutlet weak var liberalA: UISlider!
@IBAction func liberalsliderAChange(sender: UISlider) {

}


@IBOutlet weak var question2Label: UILabel!
@IBOutlet weak var liberalB: UISlider!
@IBAction func liberalsliderBChange(sender: UISlider) {

}

@IBOutlet weak var question3Label: UILabel!
@IBOutlet weak var liberalC: UISlider!
@IBAction func liberalsliderCChange(sender: UISlider) {

}


override func viewDidLoad() {
super.viewDidLoad()

questions.append(Question(text: "hello", answer: 0))
questions.append(Question(text: "g78", answer: 0))
questions.append(Question(text: "boo", answer: 0))
questions.append(Question(text: "q4", answer: 0))
questions.append(Question(text: "q5", answer: 0))
questions.append(Question(text: "788", answer: 0))
questions.append(Question(text: "756666", answer: 0))
questions.append(Question(text: "jjjjj", answer: 0))
questions.append(Question(text: "yyyyyyy", answer: 0))


loadQuestions()
}

func currentQuestion1() -> Question {
return questions[index]

}

func currentQuestion2() -> Question {
return questions[index + 1]
}

func currentQuestion3() -> Question {
return questions[index + 2]
}

func loadQuestions() {
question1Label.text = currentQuestion1().text
liberalA.value = currentQuestion1().answer

question2Label.text = currentQuestion2().text
liberalB.value = currentQuestion2().answer

question3Label.text = currentQuestion3().text
liberalC.value = currentQuestion3().answer
}

func savesliderValues(){
currentQuestion1().answer = liberalA.value
currentQuestion2().answer = liberalB.value
currentQuestion3().answer = liberalC.value
}

func incrementIndex() {
index = index + 3

}

func decrementIndex() {
index = index - 3
}


func calculatetotalScore() {
let totalScore = questions.reduce(0) { (currentvalue, question) -> Float in
currentvalue + question.answer
}
print(totalScore)
}

}

Answer
func currentQuestion3() -> Question {
    return questions[index + 2]
}

since this function access the question array with the index of current + 2, you need to adjust your next button code as follows

// count isnt 0 based so deduct 1
if index + 2 <= questions.count - 1 {
        savesliderValues()
        incrementIndex()
        loadQuestions()
        calculatetotalScore()
    } else {
        savesliderValues()
    }
Comments