-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05_Control_Flow.html
1195 lines (907 loc) · 68.5 KB
/
05_Control_Flow.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!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="1402551179317">
<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>
</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_99">
<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)至下一个 case,Swift 无需写<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("\(index) times 5 is \(index * 5)")
}
// 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("\(base) to the power of \(power) is \(answer)")
// 输出 "3 to the power of 10 is 59049"
</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>0</code>到<code>9</code>的半闭区间循环。这个计算并不需要知道每一次循环中计数器具体的值,只需要执行了正确的循环次数即可。下划线符号<code>_</code>(替代循环中的变量)能够忽略具体的值,并且不提供循环遍历时对值的访问。</p>
<p>使用<code>for-in</code>遍历一个数组所有元素:</p>
<pre><code class="lang-swift">let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
println("Hello, \(name)!")
}
// 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 = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
// 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 "Hello" {
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 < 3; ++index {
println("index is \(index)")
}
// 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 < 3; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
println("The loop statements were executed \(index) times")
// 输出 "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 < 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 < finalSquare {
// 掷骰子
if ++diceRoll == 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
if square < board.count {
// 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
}
}
println("Game over!")
</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 < 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 < finalSquare
println("Game over!")
</code></pre>
<p>检测完玩家是否踩在梯子或者蛇上之后,开始掷骰子,然后玩家向前移动<code>diceRoll</code>个方格,本轮循环结束。</p>
<p>循环条件(<code>while square < 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 <= 32 {
println("It's very cold. Consider wearing a scarf.")
}
// 输出 "It's very cold. Consider wearing a scarf."
</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 <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
// 输出 "It's not that cold. Wear a t-shirt."
</code></pre>
<p>显然,这两条分支中总有一条会被执行。由于温度已升至 40 华氏度,不算太冷,没必要再围围巾——因此,<code>else</code>分支就被触发了。</p>
<p>你可以把多个<code>if</code>语句链接在一起,像下面这样:</p>
<pre><code class="lang-swift">temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
// 输出 "It's really warm. Don't forget to wear sunscreen."
</code></pre>
<p>在上面的例子中,额外的<code>if</code>语句用于判断是不是特别热。而最后的<code>else</code>语句被保留了下来,用于打印既不冷也不热时的消息。</p>
<p>实际上,最后的<code>else</code>语句是可选的:</p>
<pre><code class="lang-swift">temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
}
</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 = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
println("\(someCharacter) is a consonant")
default:
println("\(someCharacter) is not a vowel or a consonant")
}
// 输出 "e is a vowel"
</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 = "a"
switch anotherCharacter {
case "a":
case "A":
println("The letter A")
default:
println("Not the letter A")
}
// this will report a compile-time error
</code></pre>
<p>不像 C 语言里的<code>switch</code>语句,在 Swift 中,<code>switch</code>语句不会同时匹配<code>"a"</code>和<code>"A"</code>。相反的,上面的代码会引起编译期错误:<code>case "a": 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 = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// 输出 "There are millions and millions of stars in the Milky Way."
</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("(0, 0) is at the origin")
case (_, 0):
println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// 输出 "(1, 1) is inside the box"
</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("on the x-axis with an x value of \(x)")
case (0, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}
// 输出 "on the x-axis with an x value of 2"
</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("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
println("(\(x), \(y)) is just some arbitrary point")
}
// 输出 "(1, -1) is on the line x == -y"
</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>