一个闭包能够从上下文捕获已被定义的常量和变量, 即使定义这些常量和变量的原作用域已经不存在,闭包仍能够在其函数体内引用和修改这些值
//: A UIKit based Playground for presenting user interface
import UIKit
func makeIncrementer(forIncrement amount:Int)->()->Int{
var runingTotal=0
func incrementer()-> Int{
runingTotal += amount
return runingTotal
}
return incrementer
}
作为一种优化,如果一个值没有改变或者在闭包的外面,Swift可能会使用这个值的copy而不是捕获,
Swift也处理了变量的内存管理操作,当变量不再需要时会被释放
//: A UIKit based Playground for presenting user interface
import UIKit
func makeIncrementer(forIncrement amount:Int)->()->Int{
var runingTotal=0
func incrementer()-> Int{
runingTotal += amount
return runingTotal
}
return incrementer
}
let incrementByTen=makeIncrementer(forIncrement: 10)
incrementByTen()
incrementByTen()
incrementByTen()
incrementByTen()
incrementByTen()
如果你建立了第二个incrementer它将会有一个新的、独立的runingTotal变量的引用
//: A UIKit based Playground for presenting user interface
import UIKit
func makeIncrementer(forIncrement amount:Int)->()->Int{
var runingTotal=0
func incrementer()-> Int{
runingTotal += amount
return runingTotal
}
return incrementer
}
let incrementByTen=makeIncrementer(forIncrement: 10)
incrementByTen()
incrementByTen()
incrementByTen()
incrementByTen()
incrementByTen()
let incrementBySeven=makeIncrementer(forIncrement: 7)
incrementBySeven()
incrementBySeven()
incrementBySeven()
incrementBySeven()
incrementBySeven()
闭包是引用类型
在swift中,函数和闭包都是引用类型
无论你在什么时候赋值一个函数或者闭包给常量或者变量,你实际上都是将常量和变量设置为对函数和闭包的引用
//: A UIKit based Playground for presenting user interface
import UIKit
func makeIncrementer(forIncrement amount:Int)->()->Int{
var runingTotal=0
func incrementer()-> Int{
runingTotal += amount
return runingTotal
}
return incrementer
}
let incrementByTen=makeIncrementer(forIncrement: 10)
incrementByTen()
incrementByTen()
incrementByTen()
incrementByTen()
incrementByTen()
let incrementBySeven=makeIncrementer(forIncrement: 7)
incrementBySeven()
incrementBySeven()
incrementBySeven()
incrementBySeven()
incrementBySeven()
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
闭包是引用类型
如果你分配了一个闭包给类实例的属性,并且闭包通过引用该实例或者它的成员来捕获实例,你将在闭包和实例间会产生循环引用。
标签:闭包,runingTotal,incrementBySeven,incrementByTen,Int,捕获,incrementer From: https://blog.51cto.com/u_14523369/6113222