前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >闭包(Closures)函数/表达式

闭包(Closures)函数/表达式

作者头像
gojam
发布2019-05-14 14:29:05
4400
发布2019-05-14 14:29:05
举报
文章被收录于专栏:gojam技术备忘录gojam技术备忘录

在其他语言中,闭包函数也可能叫代码块(blocks)或者匿名函数(lambdas)。

全局函数、嵌套函数和闭包表达式的区别
  • 全局函数是一种有名字但不能捕捉上下文的常量或变量值的闭包函数
  • 嵌套函数是一种有名字并且能捕捉包括它的函数的常量或变量值的闭包函数
  • 闭包表达式没有名字,轻量,能够捕捉上下文的常量或变量值

Global and nested functions, as introduced in Functions, are actually special cases of closures. Closures take one of three forms: Global functions are closures that have a name and do not capture any values. Nested functions are closures that have a name and can capture values from their enclosing function. Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context. Swift.org

可以作为参数传值

闭包函数允许被整块赋值给变量,函数可以接收闭包函数作为参数,避免了额外利用对象传值的麻烦。比如对数组排序的场景下,排序函数可以接收一个闭包函数用于描述排序的依据。

可以捕获变量并存储副本

闭包函数支持捕捉上下文中的任何常量或变量,并且一个闭包函数对象会存储捕捉到的常量或变量的副本。

Closures can capture and store references to any constants and variables from the context in which they are defined. Swift.org

Swift代码示例:

func makeCounter() -> () -> Int {
    var count = 0
    func counter() -> Int {
        count = count + 1
        return count
    }
    return counter
}

let aCount = makeCounter()
print(aCount());1
print(aCount());2

let bCount = makeCounter()
print(bCount());1
print(bCount());2

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年1月1日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 全局函数、嵌套函数和闭包表达式的区别
  • 可以作为参数传值
  • 可以捕获变量并存储副本
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档