首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CompletionHandler和闭包

CompletionHandler和闭包
EN

Stack Overflow用户
提问于 2019-01-04 15:58:17
回答 1查看 654关注 0票数 0

我有几个问题要问

1)什么是CompletionHandler和闭包,什么时候使用它? 2)闭包与CompletionHandler

这对我来说有点困惑。

EN

回答 1

Stack Overflow用户

发布于 2019-01-04 17:29:13

完成处理程序和闭包是同义词。它们在Objective-C中称为块。

您可以将它们视为在被调用时执行代码块的对象(非常类似于函数)。

代码语言:javascript
复制
// My view controller has a property that is a closure
// It also has an instance method that calls the closure
class ViewController {

    // The closure takes a String as a parameter and returns nothing (Void)
    var myClosure: ((String) -> (Void))?
    let helloString = "hello"

    // When this method is triggered, it will call my closure
    func doStuff() {
        myClosure(helloString)?
    }
}

let vc = ViewController()

// Here we define what the closure will do when it gets called
// All it does is print the parameter we've given it
vc.myClosure = { helloString in
    print(helloString) // This will print "hello"
}

// We're calling the doStuff() instance method of our view controller
// This will trigger the print statement that we defined above
vc.doStuff()

完成处理程序只是一个用于完成某个操作的闭包:一旦您完成了某项操作,您就可以调用完成处理程序来执行代码来完成该操作。

这只是一个基本的解释,有关更多细节,请查看文档:https://docs.swift.org/swift-book/LanguageGuide/Closures.html

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54035053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档