Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Why is my swift dictionary throwing an exception?

I have a simple swift dictionary. var myDictionary: [Int: Int] = [1:0, 2:0, 3:0] As a user progresses through the app the dictionary is updated like this: myDictionary[1] = 1 or myDictionary[3] = 2 This correctly results in: myDictionary = [1:1, 2:0, 3:2] When my user gets to a certain point the dictionary items are set back to an int of "0" like this: myDictionary[1] = 0 myDictionary[2] = 0 myDictionary[3] = 0

When the user starts working through the app again the app crashes when I: myDictionary[1] = 1 or any other change to the dictionary.

3 Answers

Jayden Spring
Jayden Spring
8,625 Points

Hi James,

Rather than set each value to 0, reset try reseting the dictionary using myDictionary = [:]

This will reset the dictionary to a blank one as if you had initialised it using var myDictionary = Int : Int

Let me try that. Thanks Jayden. If it works I'll let you know.

Still getting a problem. Thread 1: EXC_BAD_ACCESS(code=1, address=0x20) Still pops up and it crashes where the item in the dictionary is changed. The program works great until the dictionary is cleared and all the numbers are changed to 0. The dictionary starts empty. Here is the code: var userProgressDictionary: [Int: Int] = Int: Int In the viewDidLoad section it check for a file. If the file is there, then: userProgressDictionary = NSKeyedUnarchiver.unarchiveObjectWithFile(dataFilePathDictionary!) as [Int: Int] is called to load the object with the contents of the file. If the user stops at anytime the progress is archived in the prepareForSeque part of the code.

If there isn't a file at the dataFilePath my code calls: userProgressDictionary = [ 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0]

All this works beautifully. When all the dictionary items reach the int 3 the quiz is done and the user can reset the quiz. However I try to reset the dictionary it fails and crashes.