This is a rough example (the actual use-case I am working on has to do with the internals of PHImageManager's requestImageForAsset: function), but I'm looking for a pattern that allows you to re-run a function based on the results in the completion block.
Playground code:
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)
You can run alwaysPositive with values such as 1, 2, 9, 10, 11, etc. to see when the "re-run" message gets displayed.
Is there a common Swift pattern for what I'm trying to do?