Swift 2.0创建日历抛出

时间:2015-10-19 21:47:13

标签: xcode swift2 throw ekeventstore

我在我的应用中使用以下代码来创建日历。当我将Xcode和移动设备更新为Swift 2.0时,此行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")
    }

错误为Extra argument 'error' in call

当我重写该行时,它表示它最后会“抛出”。这是上面代码的Swift 2.0版本吗?

由于

1 个答案:

答案 0 :(得分:2)

在处理swift 2.0中的错误时,您有两种选择。您可以捕获并处理每个案例,或者如果它抛出错误则忽略该语句。以下是两种方法

-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) 

- 处理错误

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