-1

I am storing a Set into NSUserDefaults with the following code. When I close the app and launch it again it breaks. There is something screwy going on with NSUserDefaults statement, because it works fine if I omit this code. What could be the reason?

var setOfStrings: Set<String>?


 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let onlyAtFirstLaunch = NSUserDefaults.standardUserDefaults().objectForKey("arrayFromSet") as? Array<String>
        if onlyAtFirstLaunch == nil{
            setOfStrings = Set<String>()

        }else{
            let arrayFromSet = NSUserDefaults.standardUserDefaults().objectForKey("arrayFromSet") as! Array<String>

            setOfStrings! = Set(arrayFromSet)
        }
}



func applicationDidEnterBackground(application: UIApplication) {

    let arrayFromSet = Array(setOfStrings!)


    NSUserDefaults.standardUserDefaults().setObject(NSArray(array: arrayFromSet), forKey: "arrayFromSet")

    NSUserDefaults.standardUserDefaults().synchronize()
}
potato
  • 4,479
  • 7
  • 42
  • 99

1 Answers1

2

This line of code is causing the crash:

setOfStrings! = Set(arrayFromSet)

You are force unwrapping an optional var which is still nil;

Delete the "!" and it will fix the problem.

setOfStrings = Set(arrayFromSet)
Sayalee Pote
  • 511
  • 5
  • 22
wj2061
  • 6,778
  • 3
  • 36
  • 62