Files
the-swift-programming-langu…/chapter2/07_Closures.html
2014-06-15 08:30:20 +08:00

902 lines
46 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
<meta charset="UTF-8">
<title>《The Swift Programming Language》中文版</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="robots" content="index, follow">
<meta name="author" content="">
<meta name="description" content="Swift 兴趣交流群307017261">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter2/08_Enumerations.html" />
<link rel="prev" href="../chapter2/06_Functions.html" />
<meta property="og:title" content="闭包 | The Swift Programming Language 中文版">
<meta property="og:site_name" content="The Swift Programming Language 中文版">
<meta property="og:type" content="book">
<meta property="og:locale" content="en_US">
<meta property="book:author" content="https://github.com/">
<meta property="book:tag" content="GitBook">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.7" data-basepath=".." data-revision="1402792177330">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >The Swift Programming Language 中文版</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i></a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
<a href="../chapter1/chapter1.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
<a href="../chapter1/01_swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
<a href="../chapter1/02_a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
<a href="../chapter2/chapter2.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
<a href="../chapter2/01_The_Basics.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
<a href="../chapter2/02_Basic_Operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本运算符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
<a href="../chapter2/03_Strings_and_Characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
<li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
<a href="../chapter2/04_Collection_Types.html">
<i class="fa fa-check"></i> <b>2.4.</b> 集合类型
</a>
</li>
<li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
<a href="../chapter2/05_Control_Flow.html">
<i class="fa fa-check"></i> <b>2.5.</b> 控制流
</a>
</li>
<li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
<a href="../chapter2/06_Functions.html">
<i class="fa fa-check"></i> <b>2.6.</b> 函数
</a>
</li>
<li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
<a href="../chapter2/07_Closures.html">
<i class="fa fa-check"></i> <b>2.7.</b> 闭包
</a>
</li>
<li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
<a href="../chapter2/08_Enumerations.html">
<i class="fa fa-check"></i> <b>2.8.</b> 枚举
</a>
</li>
<li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
<a href="../chapter2/09_Classes_and_Structures.html">
<i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
</a>
</li>
<li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
<a href="../chapter2/10_Properties.html">
<i class="fa fa-check"></i> <b>2.10.</b> 属性
</a>
</li>
<li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
<a href="../chapter2/11_Methods.html">
<i class="fa fa-check"></i> <b>2.11.</b> 方法
</a>
</li>
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
<a href="../chapter2/12_Subscripts.html">
<i class="fa fa-check"></i> <b>2.12.</b> 下标脚本
</a>
</li>
<li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
<a href="../chapter2/13_Inheritance.html">
<i class="fa fa-check"></i> <b>2.13.</b> 继承
</a>
</li>
<li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
<a href="../chapter2/14_Initialization.html">
<i class="fa fa-check"></i> <b>2.14.</b> 构造过程
</a>
</li>
<li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
<a href="../chapter2/15_Deinitialization.html">
<i class="fa fa-check"></i> <b>2.15.</b> 析构过程
</a>
</li>
<li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
<a href="../chapter2/16_Automatic_Reference_Counting.html">
<i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
</a>
</li>
<li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
<a href="../chapter2/17_Optional_Chaining.html">
<i class="fa fa-check"></i> <b>2.17.</b> 可选链
</a>
</li>
<li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
<a href="../chapter2/18_Type_Casting.html">
<i class="fa fa-check"></i> <b>2.18.</b> 类型检查
</a>
</li>
<li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
<a href="../chapter2/19_Nested_Types.html">
<i class="fa fa-check"></i> <b>2.19.</b> 类型嵌套
</a>
</li>
<li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
<a href="../chapter2/20_Extensions.html">
<i class="fa fa-check"></i> <b>2.20.</b> 扩展
</a>
</li>
<li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
<a href="../chapter2/21_Protocols.html">
<i class="fa fa-check"></i> <b>2.21.</b> 协议
</a>
</li>
<li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
<a href="../chapter2/22_Generics.html">
<i class="fa fa-check"></i> <b>2.22.</b> 泛型
</a>
</li>
<li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
<a href="../chapter2/23_Advanced_Operators.html">
<i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
<a href="../chapter3/chapter3.html">
<i class="fa fa-check"></i> <b>3.</b> 语言参考
</a>
<ul class="articles">
<li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
<a href="../chapter3/01_About_the_Language_Reference.html">
<i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
</a>
</li>
<li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
<a href="../chapter3/02_Lexical_Structure.html">
<i class="fa fa-check"></i> <b>3.2.</b> 词法结构
</a>
</li>
<li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
<a href="../chapter3/03_Types.html">
<i class="fa fa-check"></i> <b>3.3.</b> 类型
</a>
</li>
<li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
<a href="../chapter3/04_Expressions.html">
<i class="fa fa-check"></i> <b>3.4.</b> 表达式
</a>
</li>
<li class="chapter " data-level="3.5" data-path="chapter3/10_Statements.html">
<a href="../chapter3/10_Statements.html">
<i class="fa fa-check"></i> <b>3.5.</b> 语句
</a>
</li>
<li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
<a href="../chapter3/05_Declarations.html">
<i class="fa fa-check"></i> <b>3.6.</b> 声明
</a>
</li>
<li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
<a href="../chapter3/06_Attributes.html">
<i class="fa fa-check"></i> <b>3.7.</b> 特性
</a>
</li>
<li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
<a href="../chapter3/07_Patterns.html">
<i class="fa fa-check"></i> <b>3.8.</b> 模式
</a>
</li>
<li class="chapter " data-level="3.9" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
<i class="fa fa-check"></i> <b>3.9.</b> 泛型参数
</a>
</li>
<li class="chapter " data-level="3.10" data-path="chapter3/09_Summary_of_the_Grammar.html">
<a href="../chapter3/09_Summary_of_the_Grammar.html">
<i class="fa fa-check"></i> <b>3.10.</b> 语法总结
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li><li><p style="padding-left:5px;padding-right:5px;">翻译无任何商业目的,仅供内部学习交流使用!</p></li><li><script src="http://s19.cnzz.com/z_stat.php?id=1000480711&web_id=1000480711" language="JavaScript"></script></li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 65.78947368421052%;min-width: 63.1578947368421%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
<a href="../chapter2/12_Subscripts.html" title="下标脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter done " data-progress="2.13" style="left: 23.68421052631579%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter done " data-progress="2.14" style="left: 26.31578947368421%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter done " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter done " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter done " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter done " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="类型嵌套" class="chapter done " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter done " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter done " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter done " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter done " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter done " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter done " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter done " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter done " data-progress="2.5" style="left: 60.526315789473685%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter done " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter done " data-progress="2.7" style="left: 65.78947368421052%;"></a>
<a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter " data-progress="2.8" style="left: 68.42105263157895%;"></a>
<a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter " data-progress="2.9" style="left: 71.05263157894737%;"></a>
<a href="../chapter3/chapter3.html" title="语言参考" class="chapter new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
<a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter " data-progress="3.1" style="left: 76.3157894736842%;"></a>
<a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter " data-progress="3.10" style="left: 78.94736842105263%;"></a>
<a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter " data-progress="3.2" style="left: 81.57894736842105%;"></a>
<a href="../chapter3/03_Types.html" title="类型" class="chapter " data-progress="3.3" style="left: 84.21052631578948%;"></a>
<a href="../chapter3/04_Expressions.html" title="表达式" class="chapter " data-progress="3.4" style="left: 86.84210526315789%;"></a>
<a href="../chapter3/10_Statements.html" title="语句" class="chapter " data-progress="3.5" style="left: 89.47368421052632%;"></a>
<a href="../chapter3/05_Declarations.html" title="声明" class="chapter " data-progress="3.6" style="left: 92.10526315789474%;"></a>
<a href="../chapter3/06_Attributes.html" title="特性" class="chapter " data-progress="3.7" style="left: 94.73684210526316%;"></a>
<a href="../chapter3/07_Patterns.html" title="模式" class="chapter " data-progress="3.8" style="left: 97.36842105263158%;"></a>
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter " data-progress="3.9" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_601">
<blockquote>
<p>翻译wh1100717<br>校对lyuka </p>
</blockquote>
<h1 id="-closures-">闭包Closures</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li><a href="#closure_expressions">闭包表达式Closure Expressions</a></li>
<li><a href="#trailing_closures">尾随闭包Trailing Closures</a></li>
<li><a href="#capturing_values">值捕获Capturing Values</a></li>
<li><a href="#closures_are_reference_types">闭包是引用类型Closures Are Reference Types</a></li>
</ul>
<p>闭包是自包含的函数代码块,可以在代码中被传递和使用。
Swift 中的闭包与 C 和 Objective-C 中的代码块blocks以及其他一些编程语言中的 lambdas 函数比较相似。</p>
<p>闭包可以捕获和存储其所在上下文中任意常量和变量的引用。
这就是所谓的闭合并包裹着这些常量和变量俗称闭包。Swift 会为您管理在捕获过程中涉及到的所有内存操作。</p>
<blockquote>
<p>注意:<br>如果您不熟悉捕获capturing这个概念也不用担心您可以在 <a href="#capturing_values">值捕获</a> 章节对其进行详细了解。 </p>
</blockquote>
<p><a href="../chapter2/06_Functions.html">函数</a> 章节中介绍的全局和嵌套函数实际上也是特殊的闭包,闭包采取如下三种形式之一:</p>
<ul>
<li>全局函数是一个有名字但不会捕获任何值的闭包</li>
<li>嵌套函数是一个有名字并可以捕获其封闭函数域内值的闭包</li>
<li>闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量值的匿名闭包</li>
</ul>
<p>Swift 的闭包表达式拥有简洁的风格,并鼓励在常见场景中进行语法优化,主要优化如下:</p>
<ul>
<li>利用上下文推断参数和返回值类型</li>
<li>隐式返回单表达式闭包,即单表达式闭包可以省略<code>return</code>关键字</li>
<li>参数名称缩写</li>
<li>尾随Trailing闭包语法</li>
</ul>
<p><a name="closure_expressions"></a></p>
<h2 id="-closure-expressions-">闭包表达式Closure Expressions</h2>
<p><a href="../chapter2/06_Functions.html#nested_function">嵌套函数</a> 是一个在较复杂函数中方便进行命名和定义自包含代码模块的方式。当然,有时候撰写小巧的没有完整定义和命名的类函数结构也是很有用处的,尤其是在您处理一些函数并需要将另外一些函数作为该函数的参数时。</p>
<p>闭包表达式是一种利用简洁语法构建内联闭包的方式。
闭包表达式提供了一些语法优化,使得撰写闭包变得简单明了。
下面闭包表达式的例子通过使用几次迭代展示了<code>sort</code>函数定义和语法优化的方式。
每一次迭代都用更简洁的方式描述了相同的功能。</p>
<p><a name="the_sort_function"></a></p>
<h3 id="sort-the-sort-function-">sort 函数The Sort Function</h3>
<p>Swift 标准库提供了<code>sort</code>函数,会根据您提供的基于输出类型排序的闭包函数将已知类型数组中的值进行排序。
一旦排序完成,函数会返回一个与原数组大小相同的新数组,该数组中包含已经正确排序的同类型元素。</p>
<p>下面的闭包表达式示例使用<code>sort</code>函数对一个<code>String</code>类型的数组进行字母逆序排序,以下是初始数组值:</p>
<pre><code class="lang-swift">let names = [&quot;Chris&quot;, &quot;Alex&quot;, &quot;Ewa&quot;, &quot;Barry&quot;, &quot;Daniella&quot;]
</code></pre>
<p><code>sort</code>函数需要传入两个参数:</p>
<ul>
<li>已知类型的数组</li>
<li>闭包函数,该闭包函数需要传入与数组类型相同的两个值,并返回一个布尔类型值来告诉<code>sort</code>函数当排序结束后传入的第一个参数排在第二个参数前面还是后面。如果第一个参数值出现在第二个参数值前面,排序闭包函数需要返回<code>true</code>,反之返回<code>false</code></li>
</ul>
<p>该例子对一个<code>String</code>类型的数组进行排序,因此排序闭包函数类型需为<code>(String, String) -&gt; Bool</code></p>
<p>提供排序闭包函数的一种方式是撰写一个符合其类型要求的普通函数,并将其作为<code>sort</code>函数的第二个参数传入:</p>
<pre><code class="lang-swift">func backwards(s1: String, s2: String) -&gt; Bool {
return s1 &gt; s2
}
var reversed = sort(names, backwards)
// reversed 为 [&quot;Ewa&quot;, &quot;Daniella&quot;, &quot;Chris&quot;, &quot;Barry&quot;, &quot;Alex&quot;]
</code></pre>
<p>如果第一个字符串 (<code>s1</code>) 大于第二个字符串 (<code>s2</code>)<code>backwards</code>函数返回<code>true</code>,表示在新的数组中<code>s1</code>应该出现在<code>s2</code>前。
对于字符串中的字符来说,“大于” 表示 “按照字母顺序较晚出现”。
这意味着字母<code>&quot;B&quot;</code>大于字母<code>&quot;A&quot;</code>,字符串<code>&quot;Tom&quot;</code>大于字符串<code>&quot;Tim&quot;</code>
其将进行字母逆序排序,<code>&quot;Barry&quot;</code>将会排在<code>&quot;Alex&quot;</code>之后。</p>
<p>然而,这是一个相当冗长的方式,本质上只是写了一个单表达式函数 (a &gt; b)。
在下面的例子中,利用闭合表达式语法可以更好的构造一个内联排序闭包。</p>
<p><a name="closure_expression_syntax"></a></p>
<h3 id="-closure-expression-syntax-">闭包表达式语法Closure Expression Syntax</h3>
<p>闭包表达式语法有如下一般形式:</p>
<pre><code class="lang-swift">{ (parameters) -&gt; returnType in
statements
}
</code></pre>
<p>闭包表达式语法可以使用常量、变量和<code>inout</code>类型作为参数,不提供默认值。
也可以在参数列表的最后使用可变参数。
元组也可以作为参数和返回值。</p>
<p>下面的例子展示了之前<code>backwards</code>函数对应的闭包表达式版本的代码:</p>
<pre><code class="lang-swift">reversed = sort(names, { (s1: String, s2: String) -&gt; Bool in
return s1 &gt; s2
})
</code></pre>
<p>需要注意的是内联闭包参数和返回值类型声明与<code>backwards</code>函数类型声明相同。
在这两种方式中,都写成了<code>(s1: String, s2: String) -&gt; Bool</code>
然而在内联闭包表达式中,函数和返回值类型都写在大括号内,而不是大括号外。</p>
<p>闭包的函数体部分由关键字<code>in</code>引入。
该关键字表示闭包的参数和返回值类型定义已经完成,闭包函数体即将开始。</p>
<p>因为这个闭包的函数体部分如此短以至于可以将其改写成一行代码:</p>
<pre><code class="lang-swift">reversed = sort(names, { (s1: String, s2: String) -&gt; Bool in return s1 &gt; s2 } )
</code></pre>
<p>这说明<code>sort</code>函数的整体调用保持不变,一对圆括号仍然包裹住了函数中整个参数集合。而其中一个参数现在变成了内联闭包(相比于<code>backwards</code>版本的代码)。</p>
<p><a name="inferring_type_from_context"></a></p>
<h3 id="-inferring-type-from-context-">根据上下文推断类型Inferring Type From Context</h3>
<p>因为排序闭包函数是作为<code>sort</code>函数的参数进行传入的Swift可以推断其参数和返回值的类型。
<code>sort</code>期望第二个参数是类型为<code>(String, String) -&gt; Bool</code>的函数,因此实际上<code>String</code>,<code>String</code><code>Bool</code>类型并不需要作为闭包表达式定义中的一部分。
因为所有的类型都可以被正确推断,返回箭头 (<code>-&gt;</code>) 和围绕在参数周围的括号也可以被省略:</p>
<pre><code class="lang-swift">reversed = sort(names, { s1, s2 in return s1 &gt; s2 } )
</code></pre>
<p>实际上任何情况下,通过内联闭包表达式构造的闭包作为参数传递给函数时,都可以推断出闭包的参数和返回值类型,这意味着您几乎不需要利用完整格式构造任何内联闭包。</p>
<p><a name="implicit_returns_from_single_expression_closures"></a></p>
<h3 id="-implicit-return-from-single-expression-clossures-">单表达式闭包隐式返回Implicit Return From Single-Expression Clossures</h3>
<p>单行表达式闭包可以通过隐藏<code>return</code>关键字来隐式返回单行表达式的结果,如上版本的例子可以改写为:</p>
<pre><code class="lang-swift">reversed = sort(names, { s1, s2 in s1 &gt; s2 } )
</code></pre>
<p>在这个例子中,<code>sort</code>函数的第二个参数函数类型明确了闭包必须返回一个<code>Bool</code>类型值。
因为闭包函数体只包含了一个单一表达式 (<code>s1 &gt; s2</code>),该表达式返回<code>Bool</code>类型值,因此这里没有歧义,<code>return</code>关键字可以省略。</p>
<p><a name="shorthand_argument_names"></a></p>
<h3 id="-shorthand-argument-names-">参数名称缩写Shorthand Argument Names</h3>
<p>Swift 自动为内联函数提供了参数名称缩写功能,您可以直接通过<code>$0</code>,<code>$1</code>,<code>$2</code>来顺序调用闭包的参数。</p>
<p>如果您在闭包表达式中使用参数名称缩写,您可以在闭包参数列表中省略对其的定义,并且对应参数名称缩写的类型会通过函数类型进行推断。
<code>in</code>关键字也同样可以被省略,因为此时闭包表达式完全由闭包函数体构成:</p>
<pre><code class="lang-swift">reversed = sort(names, { $0 &gt; $1 } )
</code></pre>
<p>在这个例子中,<code>$0</code><code>$1</code>表示闭包中第一个和第二个<code>String</code>类型的参数。</p>
<p><a name="operator_functions"></a></p>
<h3 id="-operator-functions-">运算符函数Operator Functions</h3>
<p>实际上还有一种更简短的方式来撰写上面例子中的闭包表达式。
Swift 的<code>String</code>类型定义了关于大于号 (<code>&gt;</code>) 的字符串实现,其作为一个函数接受两个<code>String</code>类型的参数并返回<code>Bool</code>类型的值。
而这正好与<code>sort</code>函数的第二个参数需要的函数类型相符合。
因此您可以简单地传递一个大于号Swift可以自动推断出您想使用大于号的字符串函数实现</p>
<pre><code class="lang-swift">reversed = sort(names, &gt;)
</code></pre>
<p>更多关于运算符表达式的内容请查看 <a href="../chapter2/23_Advanced_Operators.html#operator_functions">运算符函数</a></p>
<p><a name="trailing_closures"></a></p>
<h2 id="-trailing-closures-">尾随闭包Trailing Closures</h2>
<p>如果您需要将一个很长的闭包表达式作为最后一个参数传递给函数,可以使用尾随闭包来增强函数的可读性。
尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个参数调用。</p>
<pre><code class="lang-swift">func someFunctionThatTakesAClosure(closure: () -&gt; ()) {
// 函数体部分
}
// 以下是不使用尾随闭包进行函数调用
someFunctionThatTakesAClosure({
// 闭包主体部分
})
// 以下是使用尾随闭包进行函数调用
someFunctionThatTakesAClosure() {
// 闭包主体部分
}
</code></pre>
<blockquote>
<p>注意:<br>如果函数只需要闭包表达式一个参数,当您使用尾随闭包时,您甚至可以把<code>()</code>省略掉。 </p>
</blockquote>
<p>在上例中作为<code>sort</code>函数参数的字符串排序闭包可以改写为:</p>
<pre><code class="lang-swift">reversed = sort(names) { $0 &gt; $1 }
</code></pre>
<p>当闭包非常长以至于不能在一行中进行书写时,尾随闭包变得非常有用。
举例来说Swift 的<code>Array</code>类型有一个<code>map</code>方法,其获取一个闭包表达式作为其唯一参数。
数组中的每一个元素调用一次该闭包函数,并返回该元素所映射的值(也可以是不同类型的值)。
具体的映射方式和返回值类型由闭包来指定。</p>
<p>当提供给数组闭包函数后,<code>map</code>方法将返回一个新的数组,数组中包含了与原数组一一对应的映射后的值。</p>
<p>下例介绍了如何在<code>map</code>方法中使用尾随闭包将<code>Int</code>类型数组<code>[16,58,510]</code>转换为包含对应<code>String</code>类型的数组<code>[&quot;OneSix&quot;, &quot;FiveEight&quot;, &quot;FiveOneZero&quot;]</code>:</p>
<pre><code class="lang-swift">let digitNames = [
0: &quot;Zero&quot;, 1: &quot;One&quot;, 2: &quot;Two&quot;, 3: &quot;Three&quot;, 4: &quot;Four&quot;,
5: &quot;Five&quot;, 6: &quot;Six&quot;, 7: &quot;Seven&quot;, 8: &quot;Eight&quot;, 9: &quot;Nine&quot;
]
let numbers = [16, 58, 510]
</code></pre>
<p>如上代码创建了一个数字位和它们名字映射的英文版本字典。
同时定义了一个准备转换为字符串的整型数组。</p>
<p>您现在可以通过传递一个尾随闭包给<code>numbers</code><code>map</code>方法来创建对应的字符串版本数组。
需要注意的时调用<code>numbers.map</code>不需要在<code>map</code>后面包含任何括号,因为其只需要传递闭包表达式这一个参数,并且该闭包表达式参数通过尾随方式进行撰写:</p>
<pre><code class="lang-swift">let strings = numbers.map {
(var number) -&gt; String in
var output = &quot;&quot;
while number &gt; 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
// strings 常量被推断为字符串类型数组,即 String[]
// 其值为 [&quot;OneSix&quot;, &quot;FiveEight&quot;, &quot;FiveOneZero&quot;]
</code></pre>
<p><code>map</code>在数组中为每一个元素调用了闭包表达式。
您不需要指定闭包的输入参数<code>number</code>的类型,因为可以通过要映射的数组类型进行推断。</p>
<p>闭包<code>number</code>参数被声明为一个变量参数(变量的具体描述请参看<a href="../chapter2/06_Functions.html#constant_and_variable_parameters">常量参数和变量参数</a>),因此可以在闭包函数体内对其进行修改。闭包表达式制定了返回类型为<code>String</code>,以表明存储映射值的新数组类型为<code>String</code></p>
<p>闭包表达式在每次被调用的时候创建了一个字符串并返回。
其使用求余运算符 (number % 10) 计算最后一位数字并利用<code>digitNames</code>字典获取所映射的字符串。</p>
<blockquote>
<p>注意:<br>字典<code>digitNames</code>下标后跟着一个叹号 (!),因为字典下标返回一个可选值 (optional value),表明即使该 key 不存在也不会查找失败。<br>在上例中,它保证了<code>number % 10</code>可以总是作为一个<code>digitNames</code>字典的有效下标 key。<br>因此叹号可以用于强制解析 (force-unwrap) 存储在可选下标项中的<code>String</code>类型值。 </p>
</blockquote>
<p><code>digitNames</code>字典中获取的字符串被添加到输出的前部,逆序建立了一个字符串版本的数字。
(在表达式<code>number % 10</code>如果number为16则返回658返回8510返回0</p>
<p><code>number</code>变量之后除以10。
因为其是整数,在计算过程中未除尽部分被忽略。
因此 16变成了158变成了5510变成了51。</p>
<p>整个过程重复进行,直到<code>number /= 10</code>为0这时闭包会将字符串输出<code>map</code>函数则会将字符串添加到所映射的数组中。</p>
<p>上例中尾随闭包语法在函数后整洁封装了具体的闭包功能,而不再需要将整个闭包包裹在<code>map</code>函数的括号内。</p>
<p><a name="capturing_values"></a></p>
<h2 id="-capturing-values-">捕获值Capturing Values</h2>
<p>闭包可以在其定义的上下文中捕获常量或变量。
即使定义这些常量和变量的原域已经不存在,闭包仍然可以在闭包函数体内引用和修改这些值。</p>
<p>Swift最简单的闭包形式是嵌套函数也就是定义在其他函数的函数体内的函数。
嵌套函数可以捕获其外部函数所有的参数以及定义的常量和变量。</p>
<p>下例为一个叫做<code>makeIncrementor</code>的函数,其包含了一个叫做<code>incrementor</code>嵌套函数。
嵌套函数<code>incrementor</code>从上下文中捕获了两个值,<code>runningTotal</code><code>amount</code>
之后<code>makeIncrementor</code><code>incrementor</code>作为闭包返回。
每次调用<code>incrementor</code>时,其会以<code>amount</code>作为增量增加<code>runningTotal</code>的值。</p>
<pre><code class="lang-swift">func makeIncrementor(forIncrement amount: Int) -&gt; () -&gt; Int {
var runningTotal = 0
func incrementor() -&gt; Int {
runningTotal += amount
return runningTotal
}
return incrementor
}
</code></pre>
<p><code>makeIncrementor</code>返回类型为<code>() -&gt; Int</code>
这意味着其返回的是一个函数,而不是一个简单类型值。
该函数在每次调用时不接受参数只返回一个<code>Int</code>类型的值。
关于函数返回其他函数的内容,请查看<a href="../chapter2/06_Functions.html#function_types_as_return_types">函数类型作为返回类型</a></p>
<p><code>makeIncrementor</code>函数定义了一个整型变量<code>runningTotal</code>(初始为0) 用来存储当前跑步总数。
该值通过<code>incrementor</code>返回。</p>
<p><code>makeIncrementor</code>有一个<code>Int</code>类型的参数,其外部命名为<code>forIncrement</code> 内部命名为<code>amount</code>,表示每次<code>incrementor</code>被调用时<code>runningTotal</code>将要增加的量。</p>
<p><code>incrementor</code>函数用来执行实际的增加操作。
该函数简单地使<code>runningTotal</code>增加<code>amount</code>,并将其返回。</p>
<p>如果我们单独看这个函数,会发现看上去不同寻常:</p>
<pre><code class="lang-swift">func incrementor() -&gt; Int {
runningTotal += amount
return runningTotal
}
</code></pre>
<p><code>incrementor</code>函数并没有获取任何参数,但是在函数体内访问了<code>runningTotal</code><code>amount</code>变量。这是因为其通过捕获在包含它的函数体内已经存在的<code>runningTotal</code><code>amount</code>变量而实现。</p>
<p>由于没有修改<code>amount</code>变量,<code>incrementor</code>实际上捕获并存储了该变量的一个副本,而该副本随着<code>incrementor</code>一同被存储。</p>
<p>然而,因为每次调用该函数的时候都会修改<code>runningTotal</code>的值,<code>incrementor</code>捕获了当前<code>runningTotal</code>变量的引用,而不是仅仅复制该变量的初始值。捕获一个引用保证了当<code>makeIncrementor</code>结束时候并不会消失,也保证了当下一次执行<code>incrementor</code>函数时,<code>runningTotal</code>可以继续增加。</p>
<blockquote>
<p>注意:<br>Swift 会决定捕获引用还是拷贝值。<br>您不需要标注<code>amount</code>或者<code>runningTotal</code>来声明在嵌入的<code>incrementor</code>函数中的使用方式。<br>Swift 同时也处理<code>runingTotal</code>变量的内存管理操作,如果不再被<code>incrementor</code>函数使用,则会被清除。 </p>
</blockquote>
<p>下面代码为一个使用<code>makeIncrementor</code>的例子:</p>
<pre><code class="lang-swift">let incrementByTen = makeIncrementor(forIncrement: 10)
</code></pre>
<p>该例子定义了一个叫做<code>incrementByTen</code>的常量该常量指向一个每次调用会加10的<code>incrementor</code>函数。
调用这个函数多次可以得到以下结果:</p>
<pre><code class="lang-swift">incrementByTen()
// 返回的值为10
incrementByTen()
// 返回的值为20
incrementByTen()
// 返回的值为30
</code></pre>
<p>如果您创建了另一个<code>incrementor</code>,其会有一个属于自己的独立的<code>runningTotal</code>变量的引用。
下面的例子中,<code>incrementBySevne</code>捕获了一个新的<code>runningTotal</code>变量,该变量和<code>incrementByTen</code>中捕获的变量没有任何联系:</p>
<pre><code class="lang-swift">let incrementBySeven = makeIncrementor(forIncrement: 7)
incrementBySeven()
// 返回的值为7
incrementByTen()
// 返回的值为40
</code></pre>
<blockquote>
<p>注意:<br>如果您将闭包赋值给一个类实例的属性,并且该闭包通过指向该实例或其成员来捕获了该实例,您将创建一个在闭包和实例间的强引用环。<br>Swift 使用捕获列表来打破这种强引用环。更多信息,请参考 <a href="../chapter2/16_Automatic_Reference_Counting.html#strong_reference_cycles_for_closures">闭包引起的循环强引用</a></p>
</blockquote>
<p><a name="closures_are_reference_types"></a></p>
<h2 id="-closures-are-reference-types-">闭包是引用类型Closures Are Reference Types</h2>
<p>上面的例子中,<code>incrementBySeven</code><code>incrementByTen</code>是常量,但是这些常量指向的闭包仍然可以增加其捕获的变量值。
这是因为函数和闭包都是引用类型。</p>
<p>无论您将函数/闭包赋值给一个常量还是变量,您实际上都是将常量/变量的值设置为对应函数/闭包的引用。
上面的例子中,<code>incrementByTen</code>指向闭包的引用是一个常量,而并非闭包内容本身。</p>
<p>这也意味着如果您将闭包赋值给了两个不同的常量/变量,两个值都会指向同一个闭包:</p>
<pre><code class="lang-swift">let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
// 返回的值为50
</code></pre>
</section>
</div>
</div>
</div>
<a href="../chapter2/06_Functions.html" class="navigation navigation-prev " aria-label="Previous page: 函数"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/08_Enumerations.html" class="navigation navigation-next " aria-label="Next page: 枚举"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
<script src="http://yandex.st/highlightjs/8.0/styles/default.min.css"></script><script src="http://yandex.st/highlightjs/8.0/highlight.min.js"></script><script text="javascript">$('pre code').each(function(i, block) {hljs.highlightBlock(block);});</script></body>
</html>