Search code examples
xcodeswift2throwekeventstore

Swift 2.0 Create calendar throws


I was using the code below in my app to create a calendar. When I updated Xcode and mover to Swift 2.0 there is now an error on this line let calendarWasSaved = eventStore.saveCalendar(newCalendar, commit: true, error: &error).

// Save the calendar using the Event Store instance
    var error: NSError? = nil
    let calendarWasSaved = eventStore.saveCalendar(newCalendar, commit: true, error: &error)


    // Handle situation if the calendar could not be saved
    if calendarWasSaved == false {
        let alert = UIAlertController(title: "Calendar could not save", message: error?.localizedDescription, preferredStyle: .Alert)
        let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alert.addAction(OKAction)

        self.presentViewController(alert, animated: true, completion: nil)
    } else {
        insertEvent(eventStore)
        NSUserDefaults.standardUserDefaults().setObject(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar")
    }

The error is Extra argument 'error' in call

When I rewrite the line it says that it 'throws' at the end. Is this Swift 2.0's version of the code above?

Thanks


Solution

  • You have two options when dealing with errors in swift 2.0. You can catch'em and handle each case or ignore the statement if it throws error. Here is how to do both

    -Ignore if throws

    let calendarWasSaved = try? eventStore.saveCalendar(newCalendar, commit: true) // use iff calendarWasSAved doesn't affect the rest of the code (if maybe you can give it default value) 
    

    -Handle the error

    do {
       let calendarWasSaved = try eventStore.saveCalendar(newCalendar, commit: true)
    } catch (Your error type) {
         //error handling 
    } catch (_){}// Other errors that you dot care about will fall here. not necessary if you handled each case