Swift 4 中的可选闭包

Optional closures in Swift 4

我需要一个按需执行的闭包方法。

在Swift3中我曾经做过这样的事情:

// Declare closure
var checksPerformed: ((Void) -> Void)? // Declaration

// Call when needed
checksPerformed?() 

//Only executes when checksPerformed is called
checksPerformed = { _ in 
    // do stuff here
}

在Swift 4 中不再是这种情况。

修复此警告后,一切都没有像以前那样有效。 这样做的新方法是什么?

如果我将声明更新为:var checksPerformed: (() -> ())? 我得到

使用

var checksPerformed: (()->(Void))?

如果你这样做,一切都会按预期工作。

分配闭包时不要使用_in:

//Only executes when checksPerformed is called
checksPerformed = { 
    // do stuff here
}

//Call when needed
checksPerformed?() 

Distinguish between single-tuple and multiple-argument function types

// Declare closure
var checksPerformed: (() -> ())? // Declaration

// Call when needed
checksPerformed?()

//Only executes when checksPerformed is called
checksPerformed = {
    // do stuff here
}