Files
the-swift-programming-langu…/chapter2/05_Control_Flow.html
2014-06-13 23:54:58 +08:00

1196 lines
69 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 中文翻译组364279588要求对翻译感兴趣">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter2/06_Functions.html" />
<link rel="prev" href="../chapter2/04_Collection_Types.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.5" data-basepath=".." data-revision="1402674872336">
<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: 60.526315789473685%;min-width: 57.89473684210526%;"></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 " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter " 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_209">
<blockquote>
<p>翻译vclwei, coverxit, NicePiao</p>
<p>校对coverxit</p>
</blockquote>
<h1 id="-">控制流</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li><a href="#for_loops">For 循环</a></li>
<li><a href="#while_loops">While 循环</a></li>
<li><a href="#conditional_statement">条件语句</a></li>
<li><a href="#control_transfer_statements">控制转移语句Control Transfer Statements</a></li>
</ul>
<p>Swift提供了类似 C 语言的流程控制结构,包括可以多次执行任务的<code>for</code><code>while</code>循环,基于特定条件选择执行不同代码分支的<code>if</code><code>switch</code>语句,还有控制流程跳转到其他代码的<code>break</code><code>continue</code>语句。</p>
<p>除了 C 语言里面传统的for条件递增<code>for-condition-increment</code>循环Swift 还增加了<code>for-in</code>循环用来更简单地遍历数组array字典dictionary区间range字符串string和其他序列类型。</p>
<p>Swift 的<code>switch</code>语句比 C 语言中更加强大。在 C 语言中,如果某个 case 不小心漏写了<code>break</code>,这个 case 就会贯穿fallthrough至下一个 caseSwift 无需写<code>break</code>所以不会发生这种贯穿fallthrough的情况。case 还可以匹配更多的类型模式包括区间匹配range matching元组tuple和特定类型的描述。<code>switch</code>的 case 语句中匹配的值可以是由 case 体内部临时的常量或者变量决定,也可以由<code>where</code>分句描述更复杂的匹配条件。</p>
<p><a name="for_loops"></a></p>
<h2 id="for-">For 循环</h2>
<p><code>for</code>循环用来按照指定的次数多次执行一系列语句。Swift 提供两种<code>for</code>循环形式:</p>
<ul>
<li><p><code>for-in</code>用来遍历一个区间range序列sequence集合collection系列progression里面所有的元素执行一系列语句。</p>
</li>
<li><p>for条件递增<code>for-condition-increment</code>)语句,用来重复执行一系列语句直到达成特定条件达成,一般通过在每次循环完成后增加计数器的值来实现。</p>
</li>
</ul>
<p><a name="for_in"></a></p>
<h3 id="for-in">For-In</h3>
<p>你可以使用<code>for-in</code>循环来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符。</p>
<p>下面的例子用来输出乘 5 乘法表前面一部分内容:</p>
<pre><code class="lang-swift">for index in 1...5 {
println(&quot;\(index) times 5 is \(index * 5)&quot;)
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
</code></pre>
<p>例子中用来进行遍历的元素是一组使用闭区间操作符(<code>...</code>)表示的从<code>1</code><code>5</code>的数字。<code>index</code>被赋值为闭区间中的第一个数字(<code>1</code>),然后循环中的语句被执行一次。在本例中,这个循环只包含一个语句,用来输出当前<code>index</code>值所对应的乘 5 乘法表结果。该语句执行后,<code>index</code>的值被更新为闭区间中的第二个数字(<code>2</code>),之后<code>println</code>方法会再执行一次。整个过程会进行到闭区间结尾为止。</p>
<p>上面的例子中,<code>index</code>是一个每次循环遍历开始时被自动赋值的常量。这种情况下,<code>index</code>在使用前不需要声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明,而无需使用<code>let</code>关键字声明。</p>
<blockquote>
<p>注意:</p>
<p><code>index</code>常量只存在于循环的生命周期里。如果你想在循环完成后访问<code>index</code>的值,又或者想让<code>index</code>成为一个变量而不是常量,你必须在循环之前自己进行声明。</p>
</blockquote>
<p>如果你不需要知道区间内每一项的值,你可以使用下划线(<code>_</code>)替代变量名来忽略对值的访问:</p>
<pre><code class="lang-swift">let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
println(&quot;\(base) to the power of \(power) is \(answer)&quot;)
// 输出 &quot;3 to the power of 10 is 59049&quot;
</code></pre>
<p>这个例子计算 base 这个数的 power 次幂(本例中,是<code>3</code><code>10</code>次幂),从<code>1</code><code>3</code><code>0</code>次幂)开始做<code>3</code>的乘法, 进行<code>10</code>次,使用<code>1</code><code>10</code>的半闭区间循环。这个计算并不需要知道每一次循环中计数器具体的值,只需要执行了正确的循环次数即可。下划线符号<code>_</code>(替代循环中的变量)能够忽略具体的值,并且不提供循环遍历时对值的访问。</p>
<p>使用<code>for-in</code>遍历一个数组所有元素:</p>
<pre><code class="lang-swift">let names = [&quot;Anna&quot;, &quot;Alex&quot;, &quot;Brian&quot;, &quot;Jack&quot;]
for name in names {
println(&quot;Hello, \(name)!&quot;)
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
</code></pre>
<p>你也可以通过遍历一个字典来访问它的键值对key-value pairs。遍历字典时字典的每项元素会以<code>(key, value)</code>元组的形式返回,你可以在<code>for-in</code>循环中使用显式的常量名称来解读<code>(key, value)</code>元组。下面的例子中字典的键key解读为常量<code>animalName</code>,字典的值会被解读为常量<code>legCount</code></p>
<pre><code class="lang-swift">let numberOfLegs = [&quot;spider&quot;: 8, &quot;ant&quot;: 6, &quot;cat&quot;: 4]
for (animalName, legCount) in numberOfLegs {
println(&quot;\(animalName)s have \(legCount) legs&quot;)
}
// spiders have 8 legs
// ants have 6 legs
// cats have 4 legs
</code></pre>
<p>字典元素的遍历顺序和插入顺序可能不同,字典的内容在内部是无序的,所以遍历元素时不能保证顺序。关于数组和字典,详情参见<a href="../chapter2/04_Collection_Types.html">集合类型</a></p>
<p>除了数组和字典,你也可以使用<code>for-in</code>循环来遍历字符串中的字符(<code>Character</code></p>
<pre><code class="lang-swift">for character in &quot;Hello&quot; {
println(character)
}
// H
// e
// l
// l
// o
</code></pre>
<p><a name="for_condition_increment"></a></p>
<h3 id="for-for-condition-increment-">For条件递增for-condition-increment</h3>
<p>除了<code>for-in</code>循环Swift 提供使用条件判断和递增方法的标准 C 样式<code>for</code>循环:</p>
<pre><code class="lang-swift">for var index = 0; index &lt; 3; ++index {
println(&quot;index is \(index)&quot;)
}
// index is 0
// index is 1
// index is 2
</code></pre>
<p>下面是一般情况下这种循环方式的格式:</p>
<pre><code class="lang-swift">for `initialization`; `condition`; `increment` {
`statements`
}
</code></pre>
<p>和 C 语言中一样,分号将循环的定义分为 3 个部分不同的是Swift 不需要使用圆括号将“initialization; condition; increment”包括起来。</p>
<p>这个循环执行流程如下:</p>
<ol>
<li>循环首次启动时,初始化表达式(<em>initialization expression</em>)被调用一次,用来初始化循环所需的所有常量和变量。</li>
<li>条件表达式(<em>condition expression</em>)被调用,如果表达式调用结果为<code>false</code>,循环结束,继续执行<code>for</code>循环关闭大括号
<code>}</code>)之后的代码。如果表达式调用结果为<code>true</code>,则会执行大括号内部的代码(<em>statements</em>)。</li>
<li>执行所有语句(<em>statements</em>)之后,执行递增表达式(<em>increment expression</em>)。通常会增加或减少计数器的值,或者根据语句(<em>statements</em>)输出来修改某一个初始化的变量。当递增表达式运行完成后,重复执行第 2 步,条件表达式会再次执行。</li>
</ol>
<p>上述描述和循环格式等同于:</p>
<pre><code class="lang-swift">`initialization`
while `condition` {
`statements`
`increment`
}
</code></pre>
<p>在初始化表达式中声明的常量和变量(比如<code>var index = 0</code>)只在<code>for</code>循环的生命周期里有效。如果想在循环结束后访问<code>index</code>的值,你必须要在循环生命周期开始前声明<code>index</code></p>
<pre><code class="lang-swift">var index: Int
for index = 0; index &lt; 3; ++index {
println(&quot;index is \(index)&quot;)
}
// index is 0
// index is 1
// index is 2
println(&quot;The loop statements were executed \(index) times&quot;)
// 输出 &quot;The loop statements were executed 3 times
</code></pre>
<p>注意<code>index</code>在循环结束后最终的值是<code>3</code>而不是<code>2</code>。最后一次调用递增表达式<code>++index</code>会将<code>index</code>设置为<code>3</code>,从而导致<code>index &lt; 3</code>条件为<code>false</code>,并终止循环。</p>
<p><a name="while_loops"></a></p>
<h2 id="while-">While 循环</h2>
<p><code>while</code>循环运行一系列语句直到条件变成<code>false</code>。这类循环适合使用在第一次迭代前迭代次数未知的情况下。Swift 提供两种<code>while</code>循环形式:</p>
<ul>
<li><p><code>while</code>循环,每次在循环开始时计算条件是否符合;</p>
</li>
<li><p><code>do-while</code>循环,每次在循环结束时计算条件是否符合。</p>
</li>
</ul>
<p><a name="while"></a></p>
<h3 id="while">While</h3>
<p><code>while</code>循环从计算单一条件开始。如果条件为<code>true</code>,会重复运行一系列语句,直到条件变为<code>false</code></p>
<p>下面是一般情况下 <code>while</code> 循环格式:</p>
<pre><code class="lang-swift">while `condition` {
`statements`
}
</code></pre>
<p>下面的例子来玩一个叫做<em>蛇和梯子Snakes and Ladders</em>的小游戏,也叫做<em>滑道和梯子Chutes and Ladders</em></p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/snakesAndLadders_2x.png" alt="image"></p>
<p>游戏的规则如下:</p>
<ul>
<li>游戏盘面包括 25 个方格,游戏目标是达到或者超过第 25 个方格;</li>
<li>每一轮,你通过掷一个 6 边的骰子来确定你移动方块的步数,移动的路线由上图中横向的虚线所示;</li>
<li>如果在某轮结束,你移动到了梯子的底部,可以顺着梯子爬上去;</li>
<li>如果在某轮结束,你移动到了蛇的头部,你会顺着蛇的身体滑下去。</li>
</ul>
<p>游戏盘面可以使用一个<code>Int</code>数组来表达。数组的长度由一个<code>finalSquare</code>常量储存,用来初始化数组和检测最终胜利条件。游戏盘面由 26 个 <code>Int</code> 0 值初始化,而不是 25 个(由<code>0</code><code>25</code>,一共 26 个):</p>
<pre><code class="lang-swift">let finalSquare = 25
var board = Int[](count: finalSquare + 1, repeatedValue: 0)
</code></pre>
<p>一些方块被设置成有蛇或者梯子的指定值。梯子底部的方块是一个正值,使你可以向上移动,蛇头处的方块是一个负值,会让你向下移动:</p>
<pre><code class="lang-swift">board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
</code></pre>
<p>3 号方块是梯子的底部,会让你向上移动到 11 号方格,我们使用<code>board[03]</code>等于<code>+08</code>(来表示<code>11</code><code>3</code>之间的差值)。使用一元加运算符(<code>+i</code>)是为了和一元减运算符(<code>-i</code>)对称,为了让盘面代码整齐,小于 10 的数字都使用 0 补齐(这些风格上的调整都不是必须的,只是为了让代码看起来更加整洁)。</p>
<p>玩家由左下角编号为 0 的方格开始游戏。一般来说玩家第一次掷骰子后才会进入游戏盘面:</p>
<pre><code class="lang-swift">var square = 0
var diceRoll = 0
while square &lt; finalSquare {
// 掷骰子
if ++diceRoll == 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
if square &lt; board.count {
// 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
}
}
println(&quot;Game over!&quot;)
</code></pre>
<p>本例中使用了最简单的方法来模拟掷骰子。 <code>diceRoll</code>的值并不是一个随机数,而是以<code>0</code>为初始值,之后每一次<code>while</code>循环,<code>diceRoll</code>的值使用前置自增操作符(<code>++i</code>)来自增 1 ,然后检测是否超出了最大值。<code>++diceRoll</code>调用完成<em></em>,返回值等于<code>diceRoll</code>自增后的值。任何时候如果<code>diceRoll</code>的值等于7时就超过了骰子的最大值会被重置为<code>1</code>。所以<code>diceRoll</code>的取值顺序会一直是<code>1</code><code>2</code><code>3</code><code>4</code><code>5</code><code>6</code><code>1</code><code>2</code></p>
<p>掷完骰子后,玩家向前移动<code>diceRoll</code>个方格,如果玩家移动超过了第 25 个方格,这个时候游戏结束,相应地,代码会在<code>square</code>增加<code>board[square]</code>的值向前或向后移动(遇到了梯子或者蛇)之前,检测<code>square</code>的值是否小于<code>board</code><code>count</code>属性。</p>
<p>如果没有这个检测(<code>square &lt; board.count</code><code>board[square]</code>可能会越界访问<code>board</code>数组,导致错误。例如如果<code>square</code>等于<code>26</code> 代码会去尝试访问<code>board[26]</code>,超过数组的长度。</p>
<p>当本轮<code>while</code>循环运行完毕,会再检测循环条件是否需要再运行一次循环。如果玩家移动到或者超过第 25 个方格,循环条件结果为<code>false</code>,此时游戏结束。</p>
<p><code>while</code> 循环比较适合本例中的这种情况,因为在 <code>while</code> 循环开始时,我们并不知道游戏的长度或者循环的次数,只有在达成指定条件时循环才会结束。</p>
<p><a name="do_while"></a></p>
<h3 id="do-while">Do-While</h3>
<p><code>while</code>循环的另外一种形式是<code>do-while</code>,它和<code>while</code>的区别是在判断循环条件之前,先执行一次循环的代码块,然后重复循环直到条件为<code>false</code></p>
<p>下面是一般情况下 <code>do-while</code>循环的格式:</p>
<pre><code class="lang-swift">do {
`statements`
} while `condition`
</code></pre>
<p>还是蛇和梯子的游戏,使用<code>do-while</code>循环来替代<code>while</code>循环。<code>finalSquare</code><code>board</code><code>square</code><code>diceRoll</code>的值初始化同<code>while</code>循环一样:</p>
<pre><code class="lang-swift">let finalSquare = 25
var board = Int[](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
</code></pre>
<p><code>do-while</code>的循环版本,循环中<em>第一步</em>就需要去检测是否在梯子或者蛇的方块上。没有梯子会让玩家直接上到第 25 个方格,所以玩家不会通过梯子直接赢得游戏。这样在循环开始时先检测是否踩在梯子或者蛇上是安全的。</p>
<p>游戏开始时,玩家在第 0 个方格上,<code>board[0]</code>一直等于 0 不会有什么影响:</p>
<pre><code class="lang-swift">do {
// 顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
// 掷骰子
if ++diceRoll == 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
} while square &lt; finalSquare
println(&quot;Game over!&quot;)
</code></pre>
<p>检测完玩家是否踩在梯子或者蛇上之后,开始掷骰子,然后玩家向前移动<code>diceRoll</code>个方格,本轮循环结束。</p>
<p>循环条件(<code>while square &lt; finalSquare</code>)和<code>while</code>方式相同,但是只会在循环结束后进行计算。在这个游戏中,<code>do-while</code>表现得比<code>while</code>循环更好。<code>do-while</code>方式会在条件判断<code>square</code>没有超出后直接运行<code>square += board[square]</code>,这种方式可以去掉<code>while</code>版本中的数组越界判断。</p>
<p><a name="conditional_statement"></a></p>
<h2 id="-">条件语句</h2>
<p>根据特定的条件执行特定的代码通常是十分有用的,例如:当错误发生时,你可能想运行额外的代码;或者,当输入的值太大或太小时,向用户显示一条消息等。要实现这些功能,你就需要使用<em>条件语句</em></p>
<p>Swift 提供两种类型的条件语句:<code>if</code>语句和<code>switch</code>语句。通常,当条件较为简单且可能的情况很少时,使用<code>if</code>语句。而<code>switch</code>语句更适用于条件较复杂、可能情况较多且需要用到模式匹配pattern-matching的情境。</p>
<p><a name="if"></a></p>
<h3 id="if">If</h3>
<p><code>if</code>语句最简单的形式就是只包含一个条件,当且仅当该条件为<code>true</code>时,才执行相关代码:</p>
<pre><code class="lang-swift">var temperatureInFahrenheit = 30
if temperatureInFahrenheit &lt;= 32 {
println(&quot;It&#39;s very cold. Consider wearing a scarf.&quot;)
}
// 输出 &quot;It&#39;s very cold. Consider wearing a scarf.&quot;
</code></pre>
<p>上面的例子会判断温度是否小于等于 32 华氏度(水的冰点)。如果是,则打印一条消息;否则,不打印任何消息,继续执行<code>if</code>块后面的代码。</p>
<p>当然,<code>if</code>语句允许二选一,也就是当条件为<code>false</code>时,执行 <em>else 语句</em></p>
<pre><code class="lang-swift">temperatureInFahrenheit = 40
if temperatureInFahrenheit &lt;= 32 {
println(&quot;It&#39;s very cold. Consider wearing a scarf.&quot;)
} else {
println(&quot;It&#39;s not that cold. Wear a t-shirt.&quot;)
}
// 输出 &quot;It&#39;s not that cold. Wear a t-shirt.&quot;
</code></pre>
<p>显然,这两条分支中总有一条会被执行。由于温度已升至 40 华氏度,不算太冷,没必要再围围巾——因此,<code>else</code>分支就被触发了。</p>
<p>你可以把多个<code>if</code>语句链接在一起,像下面这样:</p>
<pre><code class="lang-swift">temperatureInFahrenheit = 90
if temperatureInFahrenheit &lt;= 32 {
println(&quot;It&#39;s very cold. Consider wearing a scarf.&quot;)
} else if temperatureInFahrenheit &gt;= 86 {
println(&quot;It&#39;s really warm. Don&#39;t forget to wear sunscreen.&quot;)
} else {
println(&quot;It&#39;s not that cold. Wear a t-shirt.&quot;)
}
// 输出 &quot;It&#39;s really warm. Don&#39;t forget to wear sunscreen.&quot;
</code></pre>
<p>在上面的例子中,额外的<code>if</code>语句用于判断是不是特别热。而最后的<code>else</code>语句被保留了下来,用于打印既不冷也不热时的消息。</p>
<p>实际上,最后的<code>else</code>语句是可选的:</p>
<pre><code class="lang-swift">temperatureInFahrenheit = 72
if temperatureInFahrenheit &lt;= 32 {
println(&quot;It&#39;s very cold. Consider wearing a scarf.&quot;)
} else if temperatureInFahrenheit &gt;= 86 {
println(&quot;It&#39;s really warm. Don&#39;t forget to wear sunscreen.&quot;)
}
</code></pre>
<p>在这个例子中,由于既不冷也不热,所以不会触发<code>if</code><code>else if</code>分支,也就不会打印任何消息。</p>
<p><a name="switch"></a></p>
<h3 id="switch">Switch</h3>
<p><code>switch</code>语句会尝试把某个值与若干个模式pattern进行匹配。根据第一个匹配成功的模式<code>switch</code>语句会执行对应的代码。当有可能的情况较多时,通常用<code>switch</code>语句替换<code>if</code>语句。</p>
<p><code>switch</code>语句最简单的形式就是把某个值与一个或若干个相同类型的值作比较:</p>
<pre><code class="lang-swift">switch `some value to consider` {
case `value 1`:
`respond to value 1`
case `value 2`,
`value 3`:
`respond to value 2 or 3`
default:
`otherwise, do something else`
}
</code></pre>
<p><code>switch</code>语句都由<em>多个 case</em> 构成。为了匹配某些更特定的值Swift 提供了几种更复杂的匹配模式,这些模式将在本节的稍后部分提到。</p>
<p>每一个 case 都是代码执行的一条分支,这与<code>if</code>语句类似。与之不同的是,<code>switch</code>语句会决定哪一条分支应该被执行。</p>
<p><code>switch</code>语句必须是<em>完备的</em>。这就是说,每一个可能的值都必须至少有一个 case 分支与之对应。在某些不可能涵盖所有值的情况下,你可以使用默认(<code>default</code>)分支满足该要求,这个默认分支必须在<code>switch</code>语句的最后面。</p>
<p>下面的例子使用<code>switch</code>语句来匹配一个名为<code>someCharacter</code>的小写字符:</p>
<pre><code class="lang-swift">let someCharacter: Character = &quot;e&quot;
switch someCharacter {
case &quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;:
println(&quot;\(someCharacter) is a vowel&quot;)
case &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;,
&quot;n&quot;, &quot;p&quot;, &quot;q&quot;, &quot;r&quot;, &quot;s&quot;, &quot;t&quot;, &quot;v&quot;, &quot;w&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;:
println(&quot;\(someCharacter) is a consonant&quot;)
default:
println(&quot;\(someCharacter) is not a vowel or a consonant&quot;)
}
// 输出 &quot;e is a vowel&quot;
</code></pre>
<p>在这个例子中,第一个 case 分支用于匹配五个元音,第二个 case 分支用于匹配所有的辅音。</p>
<p>由于为其它可能的字符写 case 分支没有实际的意义,因此在这个例子中使用了默认分支来处理剩下的既不是元音也不是辅音的字符——这就保证了<code>switch</code>语句的完备性。</p>
<p><a name="no_implicit_fallthrough"></a></p>
<h4 id="-no-implicit-fallthrough-">不存在隐式的贯穿No Implicit Fallthrough</h4>
<p>与 C 语言和 Objective-C 中的<code>switch</code>语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止<code>switch</code>语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用<code>break</code>语句。这使得<code>switch</code>语句更安全、更易用,也避免了因忘记写<code>break</code>语句而产生的错误。</p>
<blockquote>
<p>注意:</p>
<p>你依然可以在 case 分支中的代码执行完毕前跳出,详情请参考<a href="#break_in_a_switch_statement">Switch 语句中的 break</a></p>
</blockquote>
<p>每一个 case 分支都<em>必须</em>包含至少一条语句。像下面这样书写代码是无效的,因为第一个 case 分支是空的:</p>
<pre><code class="lang-swift">let anotherCharacter: Character = &quot;a&quot;
switch anotherCharacter {
case &quot;a&quot;:
case &quot;A&quot;:
println(&quot;The letter A&quot;)
default:
println(&quot;Not the letter A&quot;)
}
// this will report a compile-time error
</code></pre>
<p>不像 C 语言里的<code>switch</code>语句,在 Swift 中,<code>switch</code>语句不会同时匹配<code>&quot;a&quot;</code><code>&quot;A&quot;</code>。相反的,上面的代码会引起编译期错误:<code>case &quot;a&quot;: does not contain any executable statements</code>——这就避免了意外地从一个 case 分支贯穿到另外一个,使得代码更安全、也更直观。</p>
<p>一个 case 也可以包含多个模式,用逗号把它们分开(如果太长了也可以分行写):</p>
<pre><code class="lang-swift">switch `some value to consider` {
case `value 1`,
`value 2`:
`statements`
}
</code></pre>
<blockquote>
<p>注意:
如果想要贯穿至特定的 case 分支中,请使用<code>fallthrough</code>语句,详情请参考<a href="#fallthrough">贯穿Fallthrough</a></p>
</blockquote>
<p><a name="range_matching"></a></p>
<h4 id="-range-matching-">区间匹配Range Matching</h4>
<p>case 分支的模式也可以是一个值的区间。下面的例子展示了如何使用区间匹配来输出任意数字对应的自然语言格式:</p>
<pre><code class="lang-swift">let count = 3_000_000_000_000
let countedThings = &quot;stars in the Milky Way&quot;
var naturalCount: String
switch count {
case 0:
naturalCount = &quot;no&quot;
case 1...3:
naturalCount = &quot;a few&quot;
case 4...9:
naturalCount = &quot;several&quot;
case 10...99:
naturalCount = &quot;tens of&quot;
case 100...999:
naturalCount = &quot;hundreds of&quot;
case 1000...999_999:
naturalCount = &quot;thousands of&quot;
default:
naturalCount = &quot;millions and millions of&quot;
}
println(&quot;There are \(naturalCount) \(countedThings).&quot;)
// 输出 &quot;There are millions and millions of stars in the Milky Way.&quot;
</code></pre>
<p><a name="tuples"></a></p>
<h4 id="-tuple-">元组Tuple</h4>
<p>你可以使用元组在同一个<code>switch</code>语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(<code>_</code>)来匹配所有可能的值。</p>
<p>下面的例子展示了如何使用一个<code>(Int, Int)</code>类型的元组来分类下图中的点(x, y)</p>
<pre><code class="lang-swift">let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println(&quot;(0, 0) is at the origin&quot;)
case (_, 0):
println(&quot;(\(somePoint.0), 0) is on the x-axis&quot;)
case (0, _):
println(&quot;(0, \(somePoint.1)) is on the y-axis&quot;)
case (-2...2, -2...2):
println(&quot;(\(somePoint.0), \(somePoint.1)) is inside the box&quot;)
default:
println(&quot;(\(somePoint.0), \(somePoint.1)) is outside of the box&quot;)
}
// 输出 &quot;(1, 1) is inside the box&quot;
</code></pre>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/coordinateGraphSimple_2x.png" alt="image"></p>
<p>在上面的例子中,<code>switch</code>语句会判断某个点是否是原点(0, 0)是否在红色的x轴上是否在黄色y轴上是否在一个以原点为中心的4x4的矩形里或者在这个矩形外面。</p>
<p>不像 C 语言Swift 允许多个 case 匹配同一个值。实际上,在这个例子中,点(0, 0)可以匹配所有<em>四个 case</em>。但是,如果存在多个匹配,那么只会执行第一个被匹配到的 case 分支。考虑点(0, 0)会首先匹配<code>case (0, 0)</code>,因此剩下的能够匹配(0, 0)的 case 分支都会被忽视掉。</p>
<p><a name="value_bindings"></a></p>
<h4 id="-value-bindings-">值绑定Value Bindings</h4>
<p>case 分支的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用了——这种行为被称为<em>值绑定</em>value binding</p>
<p>下面的例子展示了如何在一个<code>(Int, Int)</code>类型的元组中使用值绑定来分类下图中的点(x, y)</p>
<pre><code class="lang-swift">let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println(&quot;on the x-axis with an x value of \(x)&quot;)
case (0, let y):
println(&quot;on the y-axis with a y value of \(y)&quot;)
case let (x, y):
println(&quot;somewhere else at (\(x), \(y))&quot;)
}
// 输出 &quot;on the x-axis with an x value of 2&quot;
</code></pre>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/coordinateGraphMedium_2x.png" alt="image"></p>
<p>在上面的例子中,<code>switch</code>语句会判断某个点是否在红色的x轴上是否在黄色y轴上或者不在坐标轴上。</p>
<p>这三个 case 都声明了常量<code>x</code><code>y</code>的占位符,用于临时获取元组<code>anotherPoint</code>的一个或两个值。第一个 case ——<code>case (let x, 0)</code>将匹配一个纵坐标为<code>0</code>的点,并把这个点的横坐标赋给临时的常量<code>x</code>。类似的,第二个 case ——<code>case (0, let y)</code>将匹配一个横坐标为<code>0</code>的点,并把这个点的纵坐标赋给临时的常量<code>y</code></p>
<p>一旦声明了这些临时的常量,它们就可以在其对应的 case 分支里引用。在这个例子中,它们用于简化<code>println</code>的书写。</p>
<p>请注意,这个<code>switch</code>语句不包含默认分支。这是因为最后一个 case ——<code>case let(x, y)</code>声明了一个可以匹配余下所有值的元组。这使得<code>switch</code>语句已经完备了,因此不需要再书写默认分支。</p>
<p>在上面的例子中,<code>x</code><code>y</code>是常量,这是因为没有必要在其对应的 case 分支中修改它们的值。然而,它们也可以是变量——程序将会创建临时变量,并用相应的值初始化它。修改这些变量只会影响其对应的 case 分支。</p>
<p><a name="where"></a></p>
<h4 id="where">Where</h4>
<p>case 分支的模式可以使用<code>where</code>语句来判断额外的条件。</p>
<p>下面的例子把下图中的点(x, y)进行了分类:</p>
<pre><code class="lang-swift">let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
println(&quot;(\(x), \(y)) is on the line x == y&quot;)
case let (x, y) where x == -y:
println(&quot;(\(x), \(y)) is on the line x == -y&quot;)
case let (x, y):
println(&quot;(\(x), \(y)) is just some arbitrary point&quot;)
}
// 输出 &quot;(1, -1) is on the line x == -y&quot;
</code></pre>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/coordinateGraphComplex_2x.png" alt="image"></p>
<p>在上面的例子中,<code>switch</code>语句会判断某个点是否在绿色的对角线<code>x == y</code>上,是否在紫色的对角线<code>x == -y</code>上,或者不在对角线上。</p>
<p>这三个 case 都声明了常量<code>x</code><code>y</code>的占位符,用于临时获取元组<code>yetAnotherPoint</code>的两个值。这些常量被用作<code>where</code>语句的一部分,从而创建一个动态的过滤器(filter)。当且仅当<code>where</code>语句的条件为<code>true</code>时,匹配到的 case 分支才会被执行。</p>
<p>就像是值绑定中的例子,由于最后一个 case 分支匹配了余下所有可能的值,<code>switch</code>语句就已经完备了,因此不需要再书写默认分支。</p>
<p><a name="control_transfer_statements"></a></p>
<h2 id="-control-transfer-statements-">控制转移语句Control Transfer Statements</h2>
<p>控制转移语句改变你代码的执行顺序通过它你可以实现代码的跳转。Swift有四种控制转移语句。</p>
<ul>
<li>continue</li>
<li>break</li>
<li>fallthrough</li>
<li>return</li>
</ul>
<p>我们将会在下面讨论<code>continue</code><code>break</code><code>fallthrough</code>语句。<code>return</code>语句将会在<a href="../chapter2/06_Functions.html">函数</a>章节讨论。</p>
<p><a name="continue"></a></p>
<h3 id="continue">Continue</h3>
<p><code>continue</code>语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已经执行完了”,但是并不会离开整个循环体。</p>
<blockquote>
<p>注意:</p>
<p>在一个for条件递增<code>for-condition-increment</code>)循环体中,在调用<code>continue</code>语句后,迭代增量仍然会被计算求值。循环体继续像往常一样工作,仅仅只是循环体中的执行代码会被跳过。</p>
</blockquote>
<p>下面的例子把一个小写字符串中的元音字母和空格字符移除,生成了一个含义模糊的短句:</p>
<pre><code class="lang-swift">let puzzleInput = &quot;great minds think alike&quot;
var puzzleOutput = &quot;&quot;
for character in puzzleInput {
switch character {
case &quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;, &quot; &quot;:
continue
default:
puzzleOutput += character
}
}
println(puzzleOutput)
// 输出 &quot;grtmndsthnklk&quot;
</code></pre>
<p>在上面的代码中,只要匹配到元音字母或者空格字符,就调用<code>continue</code>语句,使本次循环迭代结束,从新开始下次循环迭代。这种行为使<code>switch</code>匹配到元音字母和空格字符时不做处理,而不是让每一个匹配到的字符都被打印。</p>
<p><a name="break"></a></p>
<h3 id="break">Break</h3>
<p><code>break</code>语句会立刻结束整个控制流的执行。当你想要更早的结束一个<code>switch</code>代码块或者一个循环体时,你都可以使用<code>break</code>语句。</p>
<p><a name="break_in_a_loop_statement"></a></p>
<h4 id="-break">循环语句中的 break</h4>
<p>当在一个循环体中使用<code>break</code>时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(<code>}</code>)后的第一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。</p>
<p><a name="break_in_a_switch_statement"></a></p>
<h4 id="switch-break">Switch 语句中的 break</h4>
<p>当在一个<code>switch</code>代码块中使用<code>break</code>时,会立即中断该<code>switch</code>代码块的执行,并且跳转到表示<code>switch</code>代码块结束的大括号(<code>}</code>)后的第一行代码。</p>
<p>这种特性可以被用来匹配或者忽略一个或多个分支。因为 Swift 的<code>switch</code>需要包含所有的分支而且不允许有为空的分支,有时为了使你的意图更明显,需要特意匹配或者忽略某个分支。那么当你想忽略某个分支时,可以在该分支内写上<code>break</code>语句。当那个分支被匹配到时,分支内的<code>break</code>语句立即结束<code>switch</code>代码块。</p>
<blockquote>
<p>注意:</p>
<p>当一个<code>switch</code>分支仅仅包含注释时,会被报编译时错误。注释不是代码语句而且也不能让<code>switch</code>分支达到被忽略的效果。你总是可以使用<code>break</code>来忽略某个分支。</p>
</blockquote>
<p>下面的例子通过<code>switch</code>来判断一个<code>Character</code>值是否代表下面四种语言之一。为了简洁,多个值被包含在了同一个分支情况中。</p>
<pre><code class="lang-swift">let numberSymbol: Character = &quot;&quot; // 简体中文里的数字 3
var possibleIntegerValue: Int?
switch numberSymbol {
case &quot;1&quot;, &quot;١&quot;, &quot;&quot;, &quot;&quot;:
possibleIntegerValue = 1
case &quot;2&quot;, &quot;٢&quot;, &quot;&quot;, &quot;&quot;:
possibleIntegerValue = 2
case &quot;3&quot;, &quot;٣&quot;, &quot;&quot;, &quot;&quot;:
possibleIntegerValue = 3
case &quot;4&quot;, &quot;٤&quot;, &quot;&quot;, &quot;&quot;:
possibleIntegerValue = 4
default:
break
}
if let integerValue = possibleIntegerValue {
println(&quot;The integer value of \(numberSymbol) is \(integerValue).&quot;)
} else {
println(&quot;An integer value could not be found for \(numberSymbol).&quot;)
}
// 输出 &quot;The integer value of 三 is 3.&quot;
</code></pre>
<p>这个例子检查<code>numberSymbol</code>是否是拉丁,阿拉伯,中文或者泰语中的<code>1</code><code>4</code>之一。如果被匹配到,该<code>switch</code>分支语句给<code>Int?</code>类型变量<code>possibleIntegerValue</code>设置一个整数值。</p>
<p><code>switch</code>代码块执行完后,接下来的代码通过使用可选绑定来判断<code>possibleIntegerValue</code>是否曾经被设置过值。因为是可选类型的缘故,<code>possibleIntegerValue</code>有一个隐式的初始值<code>nil</code>,所以仅仅当<code>possibleIntegerValue</code>曾被<code>switch</code>代码块的前四个分支中的某个设置过一个值时,可选的绑定将会被判定为成功。</p>
<p>在上面的例子中,想要把<code>Character</code>所有的的可能性都枚举出来是不现实的,所以使用<code>default</code>分支来包含所有上面没有匹配到字符的情况。由于这个<code>default</code>分支不需要执行任何动作,所以它只写了一条<code>break</code>语句。一旦落入到<code>default</code>分支中后,<code>break</code>语句就完成了该分支的所有代码操作,代码继续向下,开始执行<code>if let</code>语句。</p>
<p><a name="fallthrough"></a></p>
<h3 id="-fallthrough-">贯穿Fallthrough</h3>
<p>Swift 中的<code>switch</code>不会从上一个 case 分支落入到下一个 case 分支中。相反,只要第一个匹配到的 case 分支完成了它需要执行的语句,整个<code>switch</code>代码块完成了它的执行。相比之下C 语言要求你显示的插入<code>break</code>语句到每个<code>switch</code>分支的末尾来阻止自动落入到下一个 case 分支中。Swift 的这种避免默认落入到下一个分支中的特性意味着它的<code>switch</code> 功能要比 C 语言的更加清晰和可预测,可以避免无意识地执行多个 case 分支从而引发的错误。</p>
<p>如果你确实需要 C 风格的贯穿fallthrough的特性你可以在每个需要该特性的 case 分支中使用<code>fallthrough</code>关键字。下面的例子使用<code>fallthrough</code>来创建一个数字的描述语句。</p>
<pre><code class="lang-swift">let integerToDescribe = 5
var description = &quot;The number \(integerToDescribe) is&quot;
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += &quot; a prime number, and also&quot;
fallthrough
default:
description += &quot; an integer.&quot;
}
println(description)
// 输出 &quot;The number 5 is a prime number, and also an integer.&quot;
</code></pre>
<p>这个例子定义了一个<code>String</code>类型的变量<code>description</code>并且给它设置了一个初始值。函数使用<code>switch</code>逻辑来判断<code>integerToDescribe</code>变量的值。当<code>integerToDescribe</code>的值属于列表中的质数之一时,该函数添加一段文字在<code>description</code>后,来表明这个是数字是一个质数。然后它使用<code>fallthrough</code>关键字来“贯穿”到<code>default</code>分支中。<code>default</code>分支添加一段额外的文字在<code>description</code>的最后,至此<code>switch</code>代码块执行完了。</p>
<p>如果<code>integerToDescribe</code>的值不属于列表中的任何质数,那么它不会匹配到第一个<code>switch</code>分支。而这里没有其他特别的分支情况,所以<code>integerToDescribe</code>匹配到包含所有的<code>default</code>分支中。</p>
<p><code>switch</code>代码块执行完后,使用<code>println</code>函数打印该数字的描述。在这个例子中,数字<code>5</code>被准确的识别为了一个质数。</p>
<blockquote>
<p>注意:</p>
<p><code>fallthrough</code>关键字不会检查它下一个将会落入执行的 case 中的匹配条件。<code>fallthrough</code>简单地使代码执行继续连接到下一个 case 中的执行代码,这和 C 语言标准中的<code>switch</code>语句特性是一样的。</p>
</blockquote>
<p><a name="labeled_statements"></a></p>
<h3 id="-labeled-statements-">带标签的语句Labeled Statements</h3>
<p>在 Swift 中,你可以在循环体和<code>switch</code>代码块中嵌套循环体和<code>switch</code>代码块来创造复杂的控制流结构。然而,循环体和<code>switch</code>代码块两者都可以使用<code>break</code>语句来提前结束整个方法体。因此,显示地指明<code>break</code>语句想要终止的是哪个循环体或者<code>switch</code>代码块,会很有用。类似地,如果你有许多嵌套的循环体,显示指明<code>continue</code>语句想要影响哪一个循环体也会非常有用。</p>
<p>为了实现这个目的,你可以使用标签来标记一个循环体或者<code>switch</code>代码块,当使用<code>break</code>或者<code>continue</code>时,带上这个标签,可以控制该标签代表对象的中断或者执行。</p>
<p>产生一个带标签的语句是通过在该语句的关键词的同一行前面放置一个标签,并且该标签后面还需带着一个冒号。下面是一个<code>while</code>循环体的语法,同样的规则适用于所有的循环体和<code>switch</code>代码块。</p>
<pre><code>`label name`: while `condition` {
`statements`
}
</code></pre><p>下面的例子是在一个带有标签的<code>while</code>循环体中调用<code>break</code><code>continue</code>语句,该循环体是前面章节中<em>蛇和梯子</em>的改编版本。这次,游戏增加了一条额外的规则:</p>
<ul>
<li>为了获胜,你必须<em>刚好</em>落在第 25 个方块中。</li>
</ul>
<p>如果某次掷骰子使你的移动超出第 25 个方块,你必须重新掷骰子,直到你掷出的骰子数刚好使你能落在第 25 个方块中。</p>
<p>游戏的棋盘和之前一样:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/snakesAndLadders_2x.png" alt="image"></p>
<p><code>finalSquare</code><code>board</code><code>square</code><code>diceRoll</code>的初始化也和之前一样:</p>
<pre><code class="lang-swift">let finalSquare = 25
var board = Int[](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
</code></pre>
<p>这个版本的游戏使用<code>while</code>循环体和<code>switch</code>方法块来实现游戏的逻辑。<code>while</code>循环体有一个标签名<code>gameLoop</code>,来表明它是蛇与梯子的主循环。</p>
<p><code>while</code>循环体的条件判断语句是<code>while square !=finalSquare</code>这表明你必须刚好落在方格25中。</p>
<pre><code class="lang-swift">gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// 到达最后一个方块,游戏结束
break gameLoop
case let newSquare where newSquare &gt; finalSquare:
// 超出最后一个方块,再掷一次骰子
continue gameLoop
default:
// 本次移动有效
square += diceRoll
square += board[square]
}
}
println(&quot;Game over!&quot;)
</code></pre>
<p>每次循环迭代开始时掷骰子。与之前玩家掷完骰子就立即移动不同,这里使用了<code>switch</code>来考虑每次移动可能产生的结果,从而决定玩家本次是否能够移动。</p>
<ul>
<li><p>如果骰子数刚好使玩家移动到最终的方格里,游戏结束。<code>break gameLoop</code>语句跳转控制去执行<code>while</code>循环体后的第一行代码,游戏结束。</p>
</li>
<li><p>如果骰子数将会使玩家的移动超出最后的方格,那么这种移动是不合法的,玩家需要重新掷骰子。<code>continue gameLoop</code>语句结束本次<code>while</code>循环的迭代,开始下一次循环迭代。</p>
</li>
<li><p>在剩余的所有情况中,骰子数产生的都是合法的移动。玩家向前移动骰子数个方格,然后游戏逻辑再处理玩家当前是否处于蛇头或者梯子的底部。本次循环迭代结束,控制跳转到<code>while</code>循环体的条件判断语句处,再决定是否能够继续执行下次循环迭代。</p>
</li>
</ul>
<blockquote>
<p>注意:</p>
<p>如果上述的<code>break</code>语句没有使用<code>gameLoop</code>标签,那么它将会中断<code>switch</code>代码块而不是<code>while</code>循环体。使用<code>gameLoop</code>标签清晰的表明了<code>break</code>想要中断的是哪个代码块。
同时请注意,当调用<code>continue gameLoop</code>去跳转到下一次循环迭代时,这里使用<code>gameLoop</code>标签并不是严格必须的。因为在这个游戏中,只有一个循环体,所以<code>continue</code>语句会影响到哪个循环体是没有歧义的。然而,<code>continue</code>语句使用<code>gameLoop</code>标签也是没有危害的。这样做符合标签的使用规则,同时参照旁边的<code>break gameLoop</code>,能够使游戏的逻辑更加清晰和易于理解。</p>
</blockquote>
</section>
</div>
</div>
</div>
<a href="../chapter2/04_Collection_Types.html" class="navigation navigation-prev " aria-label="Previous page: 集合类型"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/06_Functions.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>