Reputation: 517
Getting the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I am making a registration form application. The app allows users to create custom questions to be added to a form. At the moment I'm using a Singleton design pattern to pass the list of questions between the editing tab and the tab used to display the form.
My singleton class:
class Singleton {
static let sharedInstance = Singleton()
var questions: [Question] = []
}
In the editing form the user will press a button to update the form that people can then fill out. Here is that code and is also where I'm getting the error:
var mySingleton: Singleton!
@IBAction func updateForm(sender: AnyObject) {
for index in mySingleton.questions.count...questionsArray.count {
mySingleton.questions.append(questionsArray[index])
}
}
Thank you for your help.
Upvotes: 0
Views: 145
Reputation: 6657
This is where the error is occurring:
for index in mySingleton.questions.count...questionsArray.count {
mySingleton.questions.append(questionsArray[index])
}
The final index that is looped through is questionsArray.count
. When you access questionsArray[questionsArray.count]
, you are outside the bounds of the array. This index should never be accessed.
Instead, change your loop to the following:
for index in mySingleton.questions.count..<questionsArray.count {
mySingleton.questions.append(questionsArray[index])
}
The only difference is that ...
becomes ..<
, in order to leave out the last index that is causing the error.
Edit: after looking back at the code, it seems likely that mySingleton
was never set equal to anything. Before this code is executed, you could set mySingleton = Singleton.sharedInstance
, or simply get rid of mySingleton
and directly use Singleton.sharedInstance
.
Upvotes: 2