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

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



慕尼黑5688855
浏览 689回答 3
3回答

拉风的咖菲猫

假设您具有从网络下载文件的下载功能,并且希望在下载任务完成时收到通知。typealias CompletionHandler = (success:Bool) -> Voidfunc 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    }})希望能帮助到你。

慕的地10843

简单的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)}如何使用它: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")    }})

翻翻过去那场雪

我在理解答案时遇到了麻烦,因此我假设像我这样的任何其他初学者都可能遇到与我相同的问题。我的解决方案与最高答案相同,但希望对于初学者或一般难以理解的人更加清晰易懂。使用完成处理程序创建函数func yourFunctionName(finished: () -> Void) {     print("Doing something!")     finished()}使用功能     override func viewDidLoad() {          yourFunctionName {          //do something here after running your function           print("Tada!!!!")          }    }您的输出将是做某事多田希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP