Khoury Khoury - 1 month ago 11
Swift Question

Fatal error: Index out of range for in loops swift 3

Im trying to create a save to pdf method using the simplePDF framework on Github. I have several arrays and have tried to use a for in loop. Its my first go at this, but I do not understand why I am getting fatal error: Index out of range. Here is my code.

let A4paperSize = CGSize(width: 595, height: 842)
let pdf = SimplePDF(pageSize: A4paperSize)
pdf.setContentAlignment(.center)

let count = Globals.datesArray.count
var sum = 0

for index in 0...count {
pdf.addText(Globals.datesArray[index])
pdf.addText(Globals.titleArray[index])
pdf.addText(Globals.descriptionArray[index])
sum += index
}

let pdfData = pdf.generatePDFdata()


Any help is much appreciated. Thanks!

Answer

I think it should be let count = Globals.datesArray.count - 1. If Globals.count == 3, then index are [0,1,2], [3] would be out of range.