为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑5688855 2019-11-07 11:10:28
我只是对如何处理这个问题感到好奇。如果我有一个函数,并且希望在完全执行该函数时发生一些事情,如何将其添加到函数中?谢谢
查看完整描述

3 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

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


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

    }

})

希望能帮助到你。


查看完整回答
反对 回复 2019-11-07
?
慕的地10843

TA贡献1785条经验 获得超8个赞

简单的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")

    }

})


查看完整回答
反对 回复 2019-11-07
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

我在理解答案时遇到了麻烦,因此我假设像我这样的任何其他初学者都可能遇到与我相同的问题。


我的解决方案与最高答案相同,但希望对于初学者或一般难以理解的人更加清晰易懂。


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


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


     print("Doing something!")


     finished()


}

使用功能


     override func viewDidLoad() {


          yourFunctionName {


          //do something here after running your function

           print("Tada!!!!")

          }


    }

您的输出将是


做某事


多田


希望这可以帮助!


查看完整回答
反对 回复 2019-11-07
  • 3 回答
  • 0 关注
  • 682 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信