Files
the-swift-programming-langu…/chapter2/05_Control_Flow.html
2014-06-11 21:26:49 +08:00

1142 lines
66 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>控制流 | Swift 编程语言</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 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。">
<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="控制流 | Swift 编程语言">
<meta property="og:site_name" content="Swift 编程语言">
<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="1402493167130">
<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="../" >Swift 编程语言</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> Introduction</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>
</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_125">
<h1 id="-">控制流</h1>
<hr>
<p>Swift提供了类似C语言的流程控制结构包括可以多次执行任务的<code>for</code><code>while</code>循环,基于特定条件选择执行不同代码分支的<code>if</code><code>switch</code>语句,还有控制流程跳转到其他代码的<code>break</code><code>continue</code>语句。</p>
<p>除了C里面传统的 <code>for</code> 条件递增循环Swift 还增加了 <code>for-in</code> 循环,用来更简单地遍历数组(array),字典(dictionary)范围range字符串string和其他序列类型。</p>
<p>Swift 的 <code>switch</code> 语句比 C 语言中更加强大。在 C 语言中,如果某个 case 不小心漏写了 <code>break</code>,这个 case 就会“掉入”下一个 caseSwift 无需写 <code>break</code>所以不会发生这种“掉入”的情况。Case 还可以匹配更多的类型模式包括范围range匹配元组tuple和特定类型的描述。<code>switch</code> case 语句中匹配的值可以是由 case 体内部临时的常量或者变量决定,也可以由 <code>where</code> 分句描述更复杂的匹配条件。</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><code>for</code> 条件递增语句(<code>for-condition-increment</code>),用来重复执行一系列语句直到特定条件达成,一般通过在每次循环完成后增加计数器的值来实现。</p>
</li>
</ul>
<h3 id="for-in">For-In</h3>
<p>你可以使用 <code>for-in</code> 循环来遍历一个集合里面的所有元素,例如由数字表示的范围、数组中的元素、字符串中的字符。</p>
<p>下面的例子用来输出乘5乘法表前面一部分内容</p>
<pre><code>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>例子中用来进行遍历的元素是一组使用闭区间操作符(...)表示的从1到5的闭区间数字。<code>index</code> 被赋值为闭区间范围中的第一个数字1然后循环中的语句被执行一次。在本例中这个循环只包含一个语句用来输出当前 <code>index</code> 值所对应的乘5乘法表结果。该语句执行后<code>index</code> 的值被更新为闭区间范围中的第二个数字2之后 <code>println</code> 方法会再执行一次。整个过程会进行到闭区间范围结尾为止。</p>
<p>上面的例子中,<code>index</code> 是一个每次循环遍历开始时被自动赋值的常量。这种情况下,<code>index</code> 在使用前不需要声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明,而无需使用 <code>let</code> 关键字声明。</p>
<pre><code>注意:
index 常量只存在于循环的生命周期里。如果你想在循环完成后访问 index 的值,又或者想让 index 成为一个变量而不是常量,你必须在循环之前自己进行声明。
</code></pre><p>如果你不需要知道范围内每一项的值你可以使用下划线_替代变量名来忽略对值的访问</p>
<pre><code>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;)
// prints &quot;3 to the power of 10 is 59049
</code></pre><p>这个例子计算 base 这个数的 power 次幂(本例中,是 3 的 10 次幂),从 1 3 的 0 次幂)开始做 3 的乘法, 进行 10 次,使用 0 到 9 的半闭区间循环。这个计算并不需要知道每一次循环中计数器具体的值,只需要执行了正确的循环次数即可。下划线符号 _ (替代循环中的变量)能够忽略具体的值,并且不提供循环遍历时对值的访问。</p>
<p>使用 <code>for-in</code> 遍历一个数组所有元素:</p>
<pre><code>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)。遍历字典时,字典的每项元素会以 key, value元组的形式返回你可以在 <code>for-in</code> 循环中使用显式的常量名称来解读 key, value元组。下面的例子中字典的键(key)解读为常量 <code>animalName</code> ,字典的值会被解读为常量 <code>legCount</code> </p>
<pre><code>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="http://numbbbbb.github.io/the-swift-programming-language-in-chinese/chapter2/04_Collection_Types.html" target="_blank">集合类型章节</a></p>
<p>除了数组和字典,你也可以使用 <code>for-in</code> 循环来遍历字符串中的字符:</p>
<pre><code>for character in &quot;Hello&quot; {
println(character)
}
// H
// e
// l
// l
// o
</code></pre><h3 id="for-for-condition-increment-">For条件递增for-condition-increment</h3>
<p>除了 <code>for-in</code> 循环Swift 提供使用条件判断和递增方法的标准C样式 <code>for</code> 循环:</p>
<pre><code>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>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>true</code>,则会执行大括号内部的代码(<em>statements</em>)。</li>
<li>执行所有语句(<em>statements</em>)之后,执行递增表达式(<em>increment expression</em>)。通常会增加或减少计数器的值,或者根据语句(<em>statements</em>输出来修改某一个初始化的变量。当递增表达式运行完成后重复执行第2步条件表达式会再次执行。</li>
</ol>
<p>上述描述和循环格式等同于:</p>
<pre><code>initialization
while condition {
statements
increment
}
</code></pre><p>在初始化表达式中声明的常量和变量(比如 var index = 0)只在 <code>for</code> 循环的生命周期里有效。如果想在循环结束后访问 index 的值,你必须要在循环生命周期开始前声明 index。</p>
<pre><code>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;)
// prints &quot;The loop statements were executed 3 times
</code></pre><p>注意 <code>index</code> 在循环结束后最终的值是 3 而不是 2。最后一次调用递增表达式 <code>++index</code> 会将 <code>index</code> 设置为 3从而导致 <code>index &lt; 3</code> 条件为 <code>false</code>,并终止循环。</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>
<h3 id="while">While</h3>
<p><code>While</code> 循环从计算单一条件开始。如果条件为 <code>true</code>,会重复运行一系列语句,直到条件变为<code>false</code></p>
<p>下面是一般情况下 <code>while</code> 循环格式:</p>
<pre><code>while condition {
statements
}
</code></pre><p>下面的例子来玩一个叫做 <em>蛇和梯子</em> 的小游戏(也叫做 <em>滑道和梯子</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个 (由 0 到 25一共 26 个):</p>
<pre><code>let finalSquare = 25
var board = Int[](count: finalSquare + 1, repeatedValue: 0)
</code></pre><p>一些方块被设置成有蛇或者梯子的指定值。梯子底部的方块是一个正值,是你可以向上移动,蛇头处的方块是一个负值,会让你向下移动:</p>
<pre><code>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> 来表示11 和 3 之间的差值)。使用一元加运算符(+i是为了和一元减运算符-i对称为了让盘面代码整齐小于 10 的数字都使用 0 补齐(这些风格上的调整都不是必须的,只是为了让代码看起来更加整洁)。</p>
<p>玩家由左下角编号为 0 的方格开始游戏。一般来说玩家第一次掷骰子后才会进入游戏盘面:</p>
<pre><code>var square = 0
var diceRoll = 0
while square &lt; finalSquare {
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
if square &lt; board.count {
// if we&#39;re still on the board, move up or down for a snake or a ladder
square += board[square]
}
}
println(&quot;Game over!&quot;)
</code></pre><p>本例中使用了最简单的方法来模拟掷骰子。 <code>diceRoll</code> 的值并不是一个随机数,而是以 0 为初始值,之后每一次 <code>while</code> 循环,<code>diceRoll</code> 的值使用前置自增操作符(++i)来自增 1 ,然后检测是否超出了最大值。<code>++diceRoll</code> 调用完成后,返回值等于 <code>diceRoll</code> 自增后的值。任何时候如果 <code>diceRoll</code> 的值等于7时就超过了骰子的最大值会被重置为 1。所以 <code>diceRoll</code> 的取值顺序会一直是 1, 2, 3, 4, 5, 6, 1, 2。</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> 等于 26 代码会去尝试访问 <code>board[26]</code>,超过数组的长度。</p>
<p>当本轮 <code>while</code> 循环运行完毕,会再检测循环条件是否需要再运行一次循环。如果玩家移动到或者超过第 25 个方格,循环条件结果为 <code>false</code>,此时游戏结束。</p>
<p><code>while</code> 循环比较适合本例中的这种情况,因为在 <code>while</code> 循环开始时,我们并不知道游戏的长度或者循环的次数,只有在达成指定条件时循环才会结束。</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>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>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> 的循环版本,循环中第一步就需要去检测是否在梯子或者蛇的方块上。没有梯子会让玩家直接上到第 25 个方格,所以玩家不会通过梯子直接赢得游戏。这样在循环开始时先检测是否踩在梯子或者蛇上是安全的。</p>
<p>游戏开始时,玩家在第 0 个方格上,<code>board[0]</code> 一直等于 0 不会有什么影响:</p>
<pre><code>do {
// move up or down for a snake or ladder
square += board[square]
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
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></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;)
}
// prints &quot;It&#39;s very cold. Consider wearing a scarf.&quot;
</code></pre>
<p>上面的例子会判断温度是否小于等于32华氏度水的冰点。如果是则打印一条消息否则不打印任何消息继续执行<code>if</code>块后面的代码。</p>
<p>当然,<code>if</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;)
}
// prints &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;)
}
// prints &quot;It&#39;s really warm. Don&#39;t forget to wear sunscreen.&quot;
</code></pre>
<p>在上面的例子中,额外的<code>if</code>语句用于判断是不是特别热。而最后的<em>else语句</em>被保留了下来,用于打印既不冷也不热时的消息。</p>
<p>实际上,最后的<em>else语句</em>是可选的:</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>每一个<em>case</em>都是代码执行的一条分支,这与<code>if</code>语句类似。与之不同的是,<code>switch</code>语句会决定哪一条分支应该被执行。</p>
<p><code>switch</code>语句必须是完备的。这就是说,每一个可能的值都必须至少有一个<em>case</em>块与之对应。在某些不可能涵盖所有值的情况下,你可以使用默认(<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;)
}
// prints &quot;e is a vowel&quot;
</code></pre>
<p>在这个例子中,第一个<em>case</em>块用于匹配五个元音,第二个<em>case</em>块用于匹配所有的辅音。</p>
<p>由于为其它可能的字符写<em>case</em>快没有实际的意义,因此在这个例子中使用了默认块来处理剩下的既不是元音也不是辅音的字符——这就保证了<code>switch</code>语句的完备性。</p>
<h4 id="-fallthrough-">不存在隐式的贯穿(Fallthrough)</h4>
<p>与C语言和Objective-C中的<code>switch</code>语句不同,在 Swift 中,当匹配的<em>case</em>块中的代码执行完毕后,程序会终止<code>switch</code>语句,而不会继续执行下一个<em>case</em>块。这也就是说,不需要在<em>case</em>块中显式地使用<code>break</code>语句。这使得<code>switch</code>语句更安全、更易用,也避免了因忘记写<code>break</code>语句而产生的错误。</p>
<blockquote>
<p>注意:你依然可以在<em>case</em>块中的代码执行完毕前跳出,详情请参考<a href="">Switch 语句中的 Break<code>待添加链接</code></a></p>
</blockquote>
<p>每一个<em>case</em>块都<em>必须</em>包含至少一条语句。像下面这样书写代码是无效的,因为第一个<em>case</em>块是空的:</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>——这就避免了意外地从一个<em>case</em>块贯穿到另外一个,使得代码更安全、也更直观。</p>
<p>一个<em>case</em>也可以包含多个模式,用逗号把它们分开(如果太长了也可以分行写):</p>
<pre><code class="lang-swift">switch `some value to consider` {
case `value 1`,
`value 2`:
`statements`
}
</code></pre>
<blockquote>
<p>注意:如果想要贯穿特定的<em>case</em>块中,请使用<code>fallthrough</code>语句,详情请参考<a href="">贯穿 (Fallthrough)<code>待添加链接</code></a></p>
</blockquote>
<h4 id="-">范围匹配</h4>
<p><em>case</em>块的模式也可以是一个值的范围。下面的例子展示了如何使用范围匹配来输出任意数字对应的自然语言格式:</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;)
// prints &quot;There are millions and millions of stars in the Milky Way.&quot;
</code></pre>
<h4 id="-tuple-">元组 (Tuple)</h4>
<p>你可以使用元组在同一个<code>switch</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;)
}
// prints &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" width="288" height="288"></p>
<p>在上面的例子中,<code>switch</code>语句会判断某个点是否是原点(0, 0)是否在红色的x轴上是否在黄色y轴上是否在一个以原点为中心的4x4的矩形里或者在这个矩形外面。</p>
<p>不像C语言Swift 允许多个<em>case</em>匹配同一个值。实际上,在这个例子中,点(0, 0)可以匹配所有<em>四个case</em>。但是,如果存在多个匹配,那么只会执行第一个被匹配到的<em>case</em>块。考虑点(0, 0)会首先匹配<code>case (0, 0)</code>,因此剩下的能够匹配(0, 0)的<em>case</em>块都会被忽视掉。</p>
<h4 id="-value-bindings-">值绑定 (Value Bindings)</h4>
<p><em>case</em>块的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该<em>case</em>块里就可以被引用了——这种行为被称为<em>值绑定</em></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;)
}
// prints &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" width="288" height="288"></p>
<p>在上面的例子中,<code>switch</code>语句会判断某个点是否在红色的x轴上是否在黄色y轴上或者不在坐标轴上。</p>
<p>这三个<em>case</em>都声明了常量<code>x</code><code>y</code>的占位符,用于临时获取元组<code>anotherPoint</code>的一个或两个值。第一个<em>case</em>——<code>case (let x, 0)</code>将匹配一个纵坐标为<code>0</code>的点,并把这个点的横坐标赋给临时的常量<code>x</code>。类似的,第二个<em>case</em>——<code>case (0, let y)</code>将匹配一个横坐标为<code>0</code>的点,并把这个点的纵坐标赋给临时的常量<code>y</code></p>
<p>一旦声明了这些临时的常量,它们就可以在其对应的<em>case</em>块里引用。在这个例子中,它们用于简化<code>println</code>的书写。</p>
<p>请注意,这个<code>switch</code>语句不包含默认块。这是因为最后一个<em>case</em>——<code>case let(x, y)</code>声明了一个可以匹配余下所有值的元组。这使得<code>switch</code>语句已经完备了,因此不需要再书写默认块。</p>
<p>在上面的例子中,<code>x</code><code>y</code>是常量,这是因为没有必要在其对应的<em>case</em>块中修改它们的值。然而,它们也可以是变量——程序将会创建临时变量,并用相应的值初始化它。修改这些变量只会影响其对应的<em>case</em>块。</p>
<h4 id="where">Where</h4>
<p><em>case</em>块的模式可以使用<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;)
}
// prints &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" width="289" height="290"></p>
<p>在上面的例子中,<code>switch</code>语句会判断某个点是否在绿色的对角线<code>x == y</code>上,是否在紫色的对角线<code>x == -y</code>上,或者不在对角线上。</p>
<p>这三个<em>case</em>都声明了常量<code>x</code><code>y</code>的占位符,用于临时获取元组<code>yetAnotherPoint</code>的两个值。这些常量被用作<code>where</code>语句的一部分,从而创建一个动态的过滤器(filter)。当且仅当<code>where</code>语句的条件为<code></code>时,匹配到的<em>case</em>块才会被执行。</p>
<p>就像是值绑定中的例子,由于最后一个<em>case</em>块匹配了余下所有可能的值,<code>switch</code>语句就已经完备了,因此不需要再书写默认块。</p>
<h2 id="-">控制转移语句</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="http://numbbbbb.github.io/the-swift-programming-language-in-chinese/chapter2/06_Functions.html" target="_blank">函数</a>章节讨论。</p>
<h3 id="continue">Continue</h3>
<p><code>continue</code>告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已经执行完了”,但是并不会离开整个循环体。</p>
<blockquote>
<p><strong>NOTE</strong>
在一个<code>for-condition-increment</code>循环体中,在调用<code>continue</code>语句后,迭代增量仍然会被计算求值。循环体继续像往常一样工作,仅仅只是循环体中的执行代码会被跳过。</p>
</blockquote>
<p>下面的例子把一个小写字符串中的元音字母和空格字符移除,生成了一个含义模糊的短句:</p>
<pre><code>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)
// prints &quot;grtmndsthnklk&quot;
</code></pre><p>在上面的代码中,只要匹配到元音字母或者空格字符,就调用<code>continue</code>语句,使本次循环迭代结束,从新开始下次循环迭代。这种行为使<code>switch</code>匹配到元音字母和空格字符时不做处理,而不是让每一个匹配到的字符都被打印。</p>
<h3 id="break">Break</h3>
<p><code>break</code>语句会立刻结束整个控制流的执行。当你想要更早的结束一个<code>switch</code>代码块或者一个循环体时,你都可以使用<code>break</code>语句。</p>
<h4 id="-break">在循环体中使用Break</h4>
<p>当在一个循环体中使用<code>break</code>时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。</p>
<h4 id="-switch-break">在Switch代码块中使用Break</h4>
<p>当在一个<code>switch</code>代码块中使用<code>break</code>时,会立即中断该<code>switch</code>代码块的执行,并且跳转到表示<code>switch</code>代码块结束的大括号(})后的第一行代码。</p>
<p>这种特性可以被用来匹配或者忽略一个或多个分支。因为Swift语言的<code>switch</code>需要包含所有的分支而且不允许有为空的分支,有时为了使你的意图更明显,需要特意匹配或者忽略某个分支。那么当你想忽略某个分支时,可以在该分支内写上<code>break</code>语句。当那个分支被匹配到时,分支内的<code>break</code>语句立即结束<code>switch</code>代码块。</p>
<blockquote>
<p><strong>NOTE</strong>
当一个<code>switch</code>分支仅仅包含注释时,会被报编译时错误。注释不是代码语句而且也不能让<code>switch</code>分支达到被忽略的效果。你总是可以使用<code>break</code>来忽略某个分支。</p>
</blockquote>
<p>下面的例子通过<code>switch</code>来判断一个<code>Character</code>值是否代表下面四种语言之一。为了简洁,多个值被包含在了同一个分支情况中。</p>
<pre><code>let numberSymbol: Character = &quot;&quot; // Simplified Chinese for the number 3
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;)
}
// prints &quot;The integer value of 三 is 3.&quot;
</code></pre><p>这个例子检查<code>numberSymbol</code>是否是拉丁阿拉伯中文或者泰语中的1...4之一。如果被匹配到,该<code>switch</code>分支语句给<code>Int?</code>类型变量<code>possibleIntegerValue</code>设置一个整数值。</p>
<p><code>switch</code>代码块执行完后,接下来的代码通过使用可选绑定来判断&#39;possibleIntegerValue&#39;是否曾经被设置过值。因为是可选类型的缘故,&#39;possibleIntegerValue&#39;有一个隐式的初始值<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>
<h3 id="fallthrough">Fallthrough</h3>
<p>Swift语言中的<code>switch</code>不会从上一个<code>case</code>分支落入到下一个<code>case</code>分支中。相反,只要第一个匹配到的<code>case</code>分支完成了它需要执行的语句,整个<code>switch</code>代码块完成了它的执行。相比之下C语言要求你显示的插入<code>break</code>语句到每个<code>switch</code>分支的末尾来阻止自动落入到下一个<code>case</code>分支中。Swift语言的这种避免默认落入到下一个分支中的特性意味着它的<code>switch</code> 功能要比C语言的更加清晰和可预测可以避免无意识地执行多个<code>case</code>分支从而引发的错误。</p>
<p>如果你确实需要C风格的落入(fallthrough)的特性,你可以在每个需要该特性的<code>case</code>分支中使用<code>fallthrough</code>关键字。下面的例子使用<code>fallthrough</code>来创建一个数字的描述语句。</p>
<pre><code>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)
// prints &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>关键字来&quot;落入&quot;<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><strong>NOTE</strong>
<code>fallthrough</code>关键字不会检查它下一个将会落入执行的<code>case</code>中的匹配条件。<code>fallthrough</code>简单地使代码执行继续连接到下一个<code>case</code>中的执行代码这和C语言标准中的<code>switch</code>语句特性是一样的。</p>
</blockquote>
<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>语句,该循环体是上述章节中蛇梯棋游戏的改编版本。这次,游戏增加了一条额外的规则:</p>
<ul>
<li>为了获胜你必须刚好落在方格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>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>gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// diceRoll will move us to the final square, so the game is over
break gameLoop
case let newSquare where newSquare &gt; finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop
default:
// this is a valid move, so find out its effect
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><strong>NOTE</strong>
如果上述的<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://s19.cnzz.com/z_stat.php?id=1000480711&web_id=1000480711" language="JavaScript"></script></body>
</html>