一元运算符 '!'不能应用于“()”类型的操作数

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

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

在 Swift 2 迁移中出现此错误。

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

错误发生在 if (managedObjectContext.hasChanges...

因为方法save没有return值:

func save() throws

它会在失败时抛出一个错误,所以你可以这样检查 save 是否成功:

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