I'm getting the following error: 'Bool' is not a subtype of 'Void'
performBlock takes a void closure with no argument, and method itself has a single argument, so I should be able to use the following syntax for my closure. Why am i getting this compile error?
workingManagedObjectContext.performBlock {
self.workingManagedObjectContext.save(nil)
self.managedObjectContext.performBlock {
self.managedObjectContext.save(nil)
}
}
The argument to performBlock
is a closure taking no arguments and returning Void
(i.e. no return value).
If the closure consists of a single expression, the return type is inferred from
the type of that expression. The type of
self.managedObjectContext.save(nil)
is Bool
, which cannot implicitly be converted to Void
.
To fix that problem, you can add an explicit return statement:
self.managedObjectContext.performBlock {
self.managedObjectContext.save(nil)
return
}
or (better), check the return value of the save
operation instead of ignoring it:
self.managedObjectContext.performBlock {
var error : NSError?
if !self.managedObjectContext.save(&error) {
// report error
}
}
(and do the same for the outer level save).
Update: As of Swift 1.2 (Xcode 6.3), unannotated single-expression closures with non-Void return types can now be used in Void contexts. So this does now compile without errors:
self.managedObjectContext.performBlock {
self.managedObjectContext.save(nil)
// explicit "return" not needed anymore in Swift 1.2
}
(Of course it is still better to actually check the return value from the save operation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With