一、 基本概念
闭包(Closures)是自包含的功能代码块,可以在代码中使用或者用来作为参数传值。 在Swift中的闭包与C、OC中的blocks和其它编程语言(如C#)中的lambda, javascript中的函数嵌套等类似。 闭包可以捕获和存储上下文中定义的的任何常量和变量的引用。这就是所谓的变量和变量的自封闭, 因此闭包还会处理所有捕获的引用的内存管理。 全局函数和嵌套函数其实就是特殊的闭包。 闭包的形式有:
(1)全局函数都是闭包,有名字但不能捕获任何值。(4)提供了尾随闭包语法(Trailing closure syntax)
var names = ["Swift", "Arial", "Soga", "Donary"]
func backwards(firstString: String, secondString: String) -> Bool { return firstString > secondString // 降序排序 }调用:
sort(&names, backwards)
这种方式的使用相当于回调backward方法。
sort(&names, { (firstString: String, secondString: String) -> Bool in return firstString > secondString })
sort(&names, { (firstString: String, secondString: String) -> Bool in return firstString > secondString})
sort(&names, { firstString, secondString in return firstString > secondString})
sort(&names, { firstString, secondString in firstString > secondString})
sort(&names, { $0 > $1 })
sort(&names, >)
sort(&names, { (firstString: String, secondString: String) -> Bool in return firstString > secondString })
sort(&names){ (firstString, secondString) -> Bool in return firstString > secondString }
var numbers = [1,2,3] let strings = numbers.map({ (var number) -> String in var output = "" while number > 0 { output = String(number % 10) + output number /= 10 } return output })
var numbers = [1,2,3] let strings = numbers.map(){ (var number) -> String in var output = "" while number > 0 { output = String(number % 10) + output number /= 10 } return output }
var numbers = [1,2,3] let strings = numbers.map{ (var number) -> String in var output = "" while number > 0 { output = String(number % 10) + output number /= 10 } return output }
func increment(#amount: Int) -> (() -> Int) { var total = 0 func incrementAmount() -> Int { total += amount // total是外部函数体内的变量,这里是可以捕获到的 return total } return incrementAmount // 返回的是一个嵌套函数(闭包) }
let incrementByTen = increment(amount: 10) incrementByTen() // return 10,incrementByTen是一个闭包 // 这里是没有改变对increment的引用,所以会保存之前的值 incrementByTen() // return 20 incrementByTen() // return 30 let incrementByOne = increment(amount: 1) incrementByOne() // return 1 incrementByOne() // return 2 incrementByTen() // return 40 incrementByOne() // return 3
__weak typeof(self) wSelf = self;
class HTMLElement { var name: String var text: String? init(name: String, text: String?) { self.name = name self.text = text } lazy var asHtml: () -> String = { [unowned self] in if let text = self.text { return "<\(self.name)>\(self.text)</\(self.name)>" } else { return "<\(self.name)>" } } } var html = HTMLElement(name: "Node", text: "Jack") html.asHtml()
上面的代码中,self对asHtml这个闭包属性有强引用,而asHtml内部又有对self的强引用,所以我们可以使用[unowned self] 将self “弱化”。从而解除了循环引用。
class TestView: UIView { private weak var textField1: UITextField! var testClosure: ((str1: String) -> Void)? override init(frame: CGRect) { super.init(frame: frame) var size = UIScreen.mainScreen().bounds.size self.frame = CGRectMake(0, 0, size.width, kViewHeight) self.backgroundColor = UIColor.grayColor() var textField1 = UITextField(frame: CGRectMake(10, 30, 150, 30)) textField1.backgroundColor = UIColor.whiteColor() self.addSubview(textField1) self.textField1 = textField1 var btn = UIButton(frame: CGRectMake(300, 30, 50, 30)) btn.setTitle("GO", forState: UIControlState.Normal) btn.addTarget(self, action: "showResult", forControlEvents: UIControlEvents.TouchDown) self.addSubview(btn) } func showResult() { self.testClosure?(str1: self.textField1.text) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
var testClosure: ((str1: String) -> Void)?它是可空的,因为在控制器ViewController.swift中不一定完成了对testClosure闭包属性赋值的工作。所以在调用闭包的时候写成
self.testClosure?(str1: self.textField1.text)而在ViewController.swift赋值的代码如下:
class ViewController: UIViewController { @IBOutlet weak var testLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() var tab = TestView() tab.testClosure = { [unowned self] // 去除循环引用 (str1: String) -> Void in self.testLabel.text = "First Record:\(str1)" } self.view.addSubview(tab) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }