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

前端 未结 1 1187
既然无缘
既然无缘 2021-01-01 19:03

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,

相关标签:
1条回答
  • 2021-01-01 19:26

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

    0 讨论(0)
提交回复
热议问题