这是一个粗略的例子(我正在处理的实际用例与 PHImageManager 的 requestImageForAsset: 函数的内部有关),但我正在寻找一种模式,允许您根据结果重新运行函数完成块。
游乐场代码:
private func subtractTen (value: Int, completion: (success: Bool, newVal: Int, [NSObject: AnyObject]?) -> Void) -> Int {
// This is private to represent a black box.
// In my personal use-case, it's actually a Foundation method
completion(success: (value - 10 >= 0), newVal: value - 10, nil)
return value - 10
}
func alwaysPositive (value: Int) -> Int {
var foo: Int
foo = subtractTen(value) { success, newVal, _ in
if success {
print ("yay")
} else {
// I need subtractTen re-run with a new input: newVal
// and I need the resulting value in the calling function
// (in this case, "foo")
print ("re-run subtractTen with newVal, and return the value to the parent function")
}
return
}
return foo
}
alwaysPositive(10)
您可以使用诸如 1、2、9、10、11 等值运行 alwaysPositive,以查看何时显示“重新运行”消息。
我正在尝试做的事情有一个常见的 Swift 模式吗?