Swift 在执行以下两行之间添加完成

Swift 在执行以下两行之间添加完成,swift,swift2,xcode7,Swift,Swift2,Xcode7,需要在一个(相同)函数中的两行执行之间添加complete。有什么好的选择吗 例如: 任何帮助都是值得的。提前感谢…解决方案 您可以使用闭包来实现这一点。结帐 实施 这里有用于声明函数的代码 假设第一个操作是在后台线程上执行指令的函数(即,我们发出网络请求并等待响应。我们等待它获取数据,因此我们使用一个completionHandler,它是一个闭包,当我们关于第一个操作的指令完成时将调用它 调用第一个操作,我们将得到一个回调,该回调将在第一个操作的指令完成时执行。当它返回完成true时,我们就

需要在一个(相同)函数中的两行执行之间添加complete。有什么好的选择吗

例如:

任何帮助都是值得的。提前感谢…

解决方案 您可以使用闭包来实现这一点。结帐

实施 这里有用于声明函数的代码

假设第一个操作是在后台线程上执行指令的函数(即,我们发出网络请求并等待响应。我们等待它获取数据,因此我们使用一个
completionHandler
,它是一个闭包,当我们关于第一个操作的指令完成时将调用它

调用第一个操作,我们将得到一个回调,该回调将在第一个操作的指令完成时执行。当它返回
完成
true时,我们就可以调用第二个操作了

宣言 以下是您如何称呼它:

执行
您可以使用dispatch_group执行此操作。您不必等待,而且更简单。假设您有一个函数startFunction()和endFunction(),它代表您的行,第3行可以执行此操作。这是您可以执行的示例

在本例中,调用startFunction(),然后在您按下按钮时自动调用endFunction。startFunction进入dispatch_组,但该组仅在按下按钮时退出。我这样做是为了模拟解决方案的异步性质。您可以根据需要对其进行调整

class ViewController: UIViewController {

let dg = dispatch_group_create()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    startFunction()
    dispatch_group_notify(dg, dispatch_get_main_queue()) {
        self.endFunction()
    }
}

func endFunction() {
    print("endFunction")
}
func startFunction() {
    dispatch_group_enter(dg)
    print("startFunction")
}

@IBAction func buttonAction(sender:UIButton) {
    dispatch_group_leave(dg)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}


基本上,您使用一个调度组,然后输入该组并执行您的功能。然后您离开该组。当所有调用dispatch\u group\u enter的代码都离开了调度组时,您还可以使用dispatch\u notify执行一个块。

使用闭包来执行此类执行。参考链接:
// First operation
func foo1(completionHandler: (finished: Bool) -> Void) {
    // Considering that you are doing background stuff inside a block
    let foo1Block = {
        // Your instructions
        //....
        
        // When finished
        completionHandler(finished: true)
    }
    
    // Execute block
    foo1Block()
}

// Second operation
func foo2() {
   // Your instructions
}
foo1 { (finished) -> Void in
    if (finished) {
        // If the first operation is finished let's execute the next one
        self.foo2()
    }
}
class ViewController: UIViewController {

let dg = dispatch_group_create()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    startFunction()
    dispatch_group_notify(dg, dispatch_get_main_queue()) {
        self.endFunction()
    }
}

func endFunction() {
    print("endFunction")
}
func startFunction() {
    dispatch_group_enter(dg)
    print("startFunction")
}

@IBAction func buttonAction(sender:UIButton) {
    dispatch_group_leave(dg)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}