如何在Swift中使用完成处理程序创建一个函数?

tra*_*233 104 function completionhandler swift

我只是好奇我将如何处理这个问题.如果我有一个函数,并且我想在完全执行时发生某些事情,我该如何将它添加到函数中?谢谢

tou*_*bun 154

假设您有从网络下载文件的下载功能,并希望在下载任务完成时收到通知.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.: - ]

  • 这样做会很好,但出于好奇,我想知道你是否能以某种方式在你的函数中编写一个完成处理程序. (2认同)

Bob*_*bby 74

简单的Swift 4.0示例:

func method(arg: Bool, completion: (Bool) -> ()) {
    print("First line of code executed")
    // do stuff here to determine what you want to "send back".
    // we are just sending the Boolean value that was sent in "back"
    completion(arg)
}
Run Code Online (Sandbox Code Playgroud)

如何使用它:

method(arg: true, completion: { (success) -> Void in
    print("Second line of code executed")
    if success { // this will be equal to whatever value is set in this method call
          print("true")
    } else {
         print("false")
    }
})
Run Code Online (Sandbox Code Playgroud)


Cyr*_*cia 71

我无法理解答案,所以我假设像我这样的任何其他初学者都可能遇到与我相同的问题.

我的解决方案与最佳答案的解决方案相同,但希望对初学者或一般情况下难以理解的人更清晰易懂.

使用完成处理程序创建函数

func yourFunctionName(finished: () -> Void) {

     print("Doing something!")

     finished()

}
Run Code Online (Sandbox Code Playgroud)

使用该功能

     override func viewDidLoad() {

          yourFunctionName {

          //do something here after running your function
           print("Tada!!!!")
          }

    }
Run Code Online (Sandbox Code Playgroud)

你的输出将是

func yourFunctionName(finished: () -> Void) {

     print("Doing something!")

     finished()

}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


Lak*_*ngh 14

Swift 5.0 + ,简单而简短

例子:

款式一

    func methodName(completionBlock: () -> Void)  {

          print("block_Completion")
          completionBlock()
    }
Run Code Online (Sandbox Code Playgroud)

款式2

    func methodName(completionBlock: () -> ())  {

        print("block_Completion")
        completionBlock()
    }
Run Code Online (Sandbox Code Playgroud)

用:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        methodName {

            print("Doing something after Block_Completion!!")
        }
    }
Run Code Online (Sandbox Code Playgroud)

输出

block_Completion

在 Block_Completion 之后做点什么!!


ara*_*_86 11

我们可以将Closures用于此目的.请尝试以下方法

func loadHealthCareList(completionClosure: (indexes: NSMutableArray)-> ()) {
      //some code here
      completionClosure(indexes: list)
}
Run Code Online (Sandbox Code Playgroud)

在某些时候,我们可以调用此函数,如下所示.

healthIndexManager.loadHealthCareList { (indexes) -> () in
            print(indexes)
}
Run Code Online (Sandbox Code Playgroud)

关闭包的更多信息,请参阅以下链接.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html