Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - 'Bool' is not a subtype of 'Void'?

Tags:

swift

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)
    }
}
like image 277
aryaxt Avatar asked Sep 01 '14 04:09

aryaxt


1 Answers

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

like image 156
Martin R Avatar answered Nov 20 '22 12:11

Martin R