这是一个粗略的示例(我正在处理的实际用例与PHImageManager的requestImageForAsset: function的内部结构有关),但我正在寻找一种允许您根据完成块中的结果重新运行函数的模式。
游乐场代码:
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,以查看何时显示"re- run“消息。
对于我想要做的事情,有没有一个通用的Swift模式?
发布于 2016-05-10 04:50:56
看看这段代码,也许它会帮助你找到你想要的:
override func viewWillAppear(animated: Bool) {
rerunThis(0, callback: { (number_returned: Int, returned: Bool) in
println("returned: \(number_returned), \(returned)");
self.rerunThis(number_returned, callback: { (new_number_returned: Int, returned: Bool) in
println("new returned: \(new_number_returned), \(returned)");
});
});
}
func rerunThis(last_number: Int, callback: ((Int, Bool)->Void)) {
let new_value: Int = last_number+1;
var return_this: Bool = false;
if (new_value <= 1){
return_this = true;
}
callback(new_value, return_this);
}https://stackoverflow.com/questions/37125112
复制相似问题