Search code examples
swiftunary-operator

Unary operator '!' cannot be applied to an operand of type '()'


Unary operator '!' cannot be applied to an operand of type '()'

Getting this error on the Swift 2 migration.

func saveContext() {

    if let foregroundMO = VPDataManager.sharedInstance.persistentStack.managedObjectContext
    {
        var error:NSError? = nil;

        let managedObjectContext: NSManagedObjectContext = foregroundMO
        managedObjectContext.mergePolicy = NSOverwriteMergePolicy

        if (managedObjectContext.hasChanges) && !(managedObjectContext.save())
        {
            VPAnalytics.leaveBreadcrumb("AppDelegate saveContext critical error: \(error), \(error?.userInfo)")
            logError("Unresolved issue: \(error), \(error?.userInfo)")
            abort()
        }
    }
}

The error happens on if (managedObjectContext.hasChanges...


Solution

  • It's because the method save has no return value:

    func save() throws
    

    it will throw an error when failed, so you can check if save success like this:

    func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }