0

这是一个粗略的例子(我正在处理的实际用例与 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 模式吗?

4

1 回答 1

1

看看这段代码,也许它会帮助你正在寻找什么:

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);
}
于 2016-05-09T20:50:56.077 回答