Swift 笔记(六)
来源:互联网 发布:淘宝网盘 编辑:程序博客网 时间:2024/06/05 06:25
我的主力博客:半亩方塘
Closures
1、Closures are functions without names. Here's a declaration for a varible that can hold a closure:
var mutiplyClosure: (Int, Int) -> Int
You assign a closure to a variable like so:
multiplyClosure = { (a: Int, b: Int) -> Int in return a * b}With your closure variable defined, you can use it just as if it were a function, like so:
let result = multiplyClosure(4, 2)As you'd expect,
result
equals 8.There are many ways to shorten their syntax:
multiplyClosure = { (a: Int, b: Int) -> Int in a * b} multiplyClosure = { (a: Int, b: Int) in a * b}multiplyClosure = { (a, b) in a * b} multiplyClosure = { $0 * $1}2、Consider the following code:func operateOnNumbers(a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int { let result = operation(a, b) print(result) return result}You can then useoperateOnNumbers
with a closure, like so:let addClosure = { (a: Int, b: Int) -> Int in a + b}operateOnNumbers(4, 2, operation: addClosure)You can define the closure inline with the
operateOnNumbers
function call, like this:operateOnNumbers(4, 2, operation: { (a: Int, b: Int) -> Int in return a + b})
You can reduce the above to the following:operateOnNumbers(4, 2, operation: { $0 + $1})There's one more way you can simplify the syntax, but it can only be done when the closure is the final parameter passed to a function. In this case, you can move the closure outside of the function call:operateOnNumbers(4, 2) { $0 + $1}This is called trailing closure syntax.
3、The fact that closures can be used to capture variables from the enclosing scope can be extremely useful.
func countingClosure() -> (() -> Int) { var counter = 0 let incrementCounter: () -> Int = { return counter++ } return incrementCounter}The closure returned from this function will increment its internal counter each time it is called. Each time you call this function you get a different counter.
For example, this could be used like so:
let counter1 = countingClosure()let counter2 = countingClosure()counter1() // 0counter2() // 0counter1() // 1counter1() // 2counter2() // 1
The two counters created by the function are mutually exclusive and count independently. Neat!
- Swift 笔记(六)
- 学习Swift笔记 (六)
- Swift语言学习笔记(六)
- Swift 笔记 六: Swift 函数详解
- 字符和字符串—Swift学习笔记(六)
- swift UITableView(六)
- swift 笔记 (六) —— 函数
- 自学Swift-斯坦福笔记整理(六)
- 【Swift】学习笔记(六)——函数
- Swift学习笔记(六)枚举类型
- iOS学习笔记46-Swift(六)扩展
- Swift的数据类型(六)
- (原创)SpriteKit+Swift学习笔记(六)-生成大量精灵
- (原创)SpriteKit+Swift学习笔记(六)-生成大量精灵
- swift自学笔记(六)(构造方法、析构方法)
- swift学习笔记(六)——基础语法的总结
- Swift学习笔记(六)——变量的默认初始化值的问题
- The Swift Programming Language学习笔记(六)——控制流
- 基本字符串压缩
- 快速排序和查找第K大元素
- 第一章:mycat读写分离与容灾实验
- CodeForces 276E Little Girl and Problem on Trees 树状数组
- 常用的点击搜索框显示下拉框并实时刷新用户输入的内容
- Swift 笔记(六)
- 编译器错误信息: CS0433: 类型 同时存在于
- 1014: [JSOI2008]火星人prefix
- 键盘过滤驱动蓝屏问题
- 逻辑运算符&与&&的区别,|与||的区别
- iOS适配的相关内容的整理
- 简单游戏——贪吃蛇
- Android继承AppCompatActivity后实现全屏设置
- 3.1 依赖倒置原则的定义