Swift語言精要-閉包(Closure)

閉包(Closure)這個概念若是沒學過Swift的人應該也不會陌生。前端

學過Javascript的朋友應該知道,在Javascript中咱們常常會討論閉包,不少前端工程師的面試題也會問到什麼是閉包。面試

那麼,什麼是閉包呢?swift

讓咱們看下在Javascript中閉包的解釋:數組

Closures are functions that have access to variables from another function’s scope. 前端工程師

(This is often accomplished by creating a function inside a function. )閉包

閉包是一個函數可以訪問另一個函數做用域內變量。app

(這一般經過在一個函數內申明另外一個函數來實現)ide

經過上面的定義咱們不難判斷,閉包具有如下兩點特徵:函數

1. 閉包是函數測試

2. 閉包是函數內部的函數

3. 閉包能夠訪問另外一個函數的變量

咱們先來看下Javascipt閉包的例子:

function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if (value1 < value2) { 
            return -1;
        } else if (value1 > value2) { 
            return 1;
        } else { 
            return 0;
        } 
    };
}

 測試代碼:

var compare = createComparisonFunction(「name」);
var result = compare({ name: 「Nicholas」, age: 35 }, { name: 「Greg」, age: 28 });
console.log(result); // 1

 

上面的Javascript代碼中咱們能夠看到,

createComparisonFunction函數內部申明的匿名函數能夠訪問createComparisonFunction函數自己的參數,這正符合了咱們閉包的定義。

 

好了,Swift中閉包大體也是相似的,咱們來看下閉包在Swift中的定義:

Closures are discrete bundles of functionality that can be used in your application to accomplish specific tasks.

閉包是用來在你的應用程序內部完成某些特殊任務的一些彼此互不相關的函數集。

讀着有些拗口,仍是讓咱們用例子來講話吧,看下下面的例子:

咱們先來看一個不適用閉包的數組排序的例子

 

import Cocoa

// 不使用閉包
var counts = [1, 6, 2, 28, 13, 2, 9, 100, 30]

func sortAscending(i: Int, j: Int) -> Bool {
    return i < j
}

let sortedCounts = counts.sort(sortAscending)

 

如今,咱們看下,使用閉包代碼會變得更加簡潔

import Cocoa

// 使用閉包
var counts = [1, 6, 2, 28, 13, 2, 9, 100, 30]

let sortedCounts = counts.sort({
    (i: Int, j: Int) -> Bool in 
        return i < j
})

 

Swift的閉包語法:

{(parameters) -> [return type] in
  // Code
}

 

經過類型推斷(type inference)讓閉包變得更加簡潔:

import Cocoa

var counts = [1, 6, 2, 28, 13, 2, 9, 100, 30]

let sortedCounts = counts.sort({ i, j in i < j })

 

 經過參數佔位符讓代碼變得更簡潔:

import Cocoa

var counts = [1, 6, 2, 28, 13, 2, 9, 100, 30]

let sortedCounts = counts.sort({ $0 < $1 })

不難判斷,上面的代碼$0表明了第一個參數也就是i, 而$1表明了第一個參數也就是j。

 

哇撒,代碼變得愈來愈短了嘛,還能夠再短些嗎?

答案是能夠的!

還記得C++的內聯函(inline function)數嘛,在swift中咱們也有!

把括號去掉就是了!

因而,代碼變成了以下的樣子:

 

import Cocoa

var counts = [1, 6, 2, 28, 13, 2, 9, 100, 30]

let sortedCounts = counts.sort { $0 < $1 }
相關文章
相關標籤/搜索