-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy path06_Functions.html
1004 lines (727 loc) · 54.8 KB
/
06_Functions.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>
<meta charset="UTF-8">
<title>《The Swift Programming Language》中文版</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="generator" content="GitBook 0.5.2">
<meta name="HandheldFriendly" content="true"/>
<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">
<link rel="next" href="../chapter2/07_Closures.html" />
<link rel="prev" href="../chapter2/05_Control_Flow.html" />
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.6" data-basepath=".." data-revision="1402903834498">
<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: 63.1578947368421%;min-width: 60.526315789473685%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
<a href="../chapter2/12_Subscripts.html" title="下标脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter done " data-progress="2.13" style="left: 23.68421052631579%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter done " data-progress="2.14" style="left: 26.31578947368421%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter done " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter done " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter done " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter done " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="嵌套类型" class="chapter done " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter done " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter done " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter done " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter done " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter done " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter done " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter done " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter done " data-progress="2.5" style="left: 60.526315789473685%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter done " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter " 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_98">
<blockquote>
<p>翻译:<a href="https://github.com/honghaoz" target="_blank">honghaoz</a><br>校对:<a href="https://github.com/LunaticM" target="_blank">LunaticM</a></p>
</blockquote>
<h1 id="-functions-">函数(Functions)</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li><a href="#Defining_and_Calling_Functions">函数定义与调用(Defining and Calling Functions)</a></li>
<li><a href="#Function_Parameters_and_Return_Values">函数参数与返回值(Function Parameters and Return Values)</a></li>
<li><a href="#Function_Parameter_Names">函数参数名称(Function Parameter Names)</a></li>
<li><a href="#Function_Types">函数类型(Function Types)</a></li>
<li><a href="#Nested_Functions">函数嵌套(Nested Functions)</a></li>
</ul>
<p>函数是用来完成特定任务的独立的代码块。你给一个函数起一个合适的名字,用来标识函数做什么,并且当函数需要执行的时候,这个名字会被“调用”。</p>
<p>Swift 统一的函数语法足够灵活,可以用来表示任何函数,包括从最简单的没有参数名字的 C 风格函数,到复杂的带局部和外部参数名的 Objective-C 风格函数。参数可以提供默认值,以简化函数调用。参数也可以既当做传入参数,也当做传出参数,也就是说,一旦函数执行结束,传入的参数值可以被修改。</p>
<p>在 Swift 中,每个函数都有一种类型,包括函数的参数值类型和返回值类型。你可以把函数类型当做任何其他普通变量类型一样处理,这样就可以更简单地把函数当做别的函数的参数,也可以从其他函数中返回函数。函数的定义可以写在在其他函数定义中,这样可以在嵌套函数范围内实现功能封装。</p>
<p><a name="Defining_and_Calling_Functions"></a></p>
<h2 id="-defining-and-calling-functions-">函数的定义与调用(Defining and Calling Functions)</h2>
<p>当你定义一个函数时,你可以定义一个或多个有名字和类型的值,作为函数的输入(称为参数,parameters),也可以定义某种类型的值作为函数执行结束的输出(称为返回类型)。</p>
<p>每个函数有个函数名,用来描述函数执行的任务。要使用一个函数时,你用函数名“调用”,并传给它匹配的输入值(称作实参,arguments)。一个函数的实参必须与函数参数表里参数的顺序一致。</p>
<p>在下面例子中的函数叫做<code>"greetingForPerson"</code>,之所以叫这个名字是因为这个函数用一个人的名字当做输入,并返回给这个人的问候语。为了完成这个任务,你定义一个输入参数-一个叫做 <code>personName</code> 的 <code>String</code> 值,和一个包含给这个人问候语的 <code>String</code> 类型的返回值:</p>
<pre><code class="lang-swift">func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!"
return greeting
}
</code></pre>
<p>所有的这些信息汇总起来成为函数的定义,并以 <code>func</code> 作为前缀。指定函数返回类型时,用返回箭头 <code>-></code>(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示。</p>
<p>该定义描述了函数做什么,它期望接收什么和执行结束时它返回的结果是什么。这样的定义使的函数可以在别的地方以一种清晰的方式被调用:</p>
<pre><code class="lang-swift">println(sayHello("Anna"))
// prints "Hello, Anna!"
println(sayHello("Brian"))
// prints "Hello, Brian!"
</code></pre>
<p>调用 <code>sayHello</code> 函数时,在圆括号中传给它一个 <code>String</code> 类型的实参。因为这个函数返回一个 <code>String</code> 类型的值,<code>sayHello</code> 可以被包含在 <code>println</code> 的调用中,用来输出这个函数的返回值,正如上面所示。</p>
<p>在 <code>sayHello</code> 的函数体中,先定义了一个新的名为 <code>greeting</code> 的 <code>String</code> 常量,同时赋值了给 <code>personName</code> 的一个简单问候消息。然后用 <code>return</code> 关键字把这个问候返回出去。一旦 <code>return greeting</code> 被调用,该函数结束它的执行并返回 <code>greeting</code> 的当前值。</p>
<p>你可以用不同的输入值多次调用 <code>sayHello</code>。上面的例子展示的是用<code>"Anna"</code>和<code>"Brian"</code>调用的结果,该函数分别返回了不同的结果。</p>
<p>为了简化这个函数的定义,可以将问候消息的创建和返回写成一句:</p>
<pre><code class="lang-swift">func sayHelloAgain(personName: String) -> String {
return "Hello again, " + personName + "!"
}
println(sayHelloAgain("Anna"))
// prints "Hello again, Anna!"
</code></pre>
<p><a name="Function_Parameters_and_Return_Values"></a></p>
<h2 id="-function-parameters-and-return-values-">函数参数与返回值(Function Parameters and Return Values)</h2>
<p>函数参数与返回值在Swift中极为灵活。你可以定义任何类型的函数,包括从只带一个未名参数的简单函数到复杂的带有表达性参数名和不同参数选项的复杂函数。</p>
<h3 id="-multiple-input-parameters-">多重输入参数(Multiple Input Parameters)</h3>
<p>函数可以有多个输入参数,写在圆括号中,用逗号分隔。</p>
<p>下面这个函数用一个半开区间的开始点和结束点,计算出这个范围内包含多少数字:</p>
<pre><code class="lang-swift">func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"
</code></pre>
<h3 id="-functions-without-parameters-">无参函数(Functions Without Parameters)</h3>
<p>函数可以没有参数。下面这个函数就是一个无参函数,当被调用时,它返回固定的 <code>String</code> 消息:</p>
<pre><code class="lang-swift">func sayHelloWorld() -> String {
return "hello, world"
}
println(sayHelloWorld())
// prints "hello, world"
</code></pre>
<p>尽管这个函数没有参数,但是定义中在函数名后还是需要一对圆括号。当被调用时,也需要在函数名后写一对圆括号。</p>
<h3 id="-functions-without-return-values-">无返回值函数(Functions Without Return Values)</h3>
<p>函数可以没有返回值。下面是 <code>sayHello</code> 函数的另一个版本,叫 <code>waveGoodbye</code>,这个函数直接输出 <code>String</code> 值,而不是返回它:</p>
<pre><code class="lang-swift">func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"
</code></pre>
<p>因为这个函数不需要返回值,所以这个函数的定义中没有返回箭头(->)和返回类型。</p>
<blockquote>
<p>注意:<br>严格上来说,虽然没有返回值被定义,<code>sayGoodbye</code> 函数依然返回了值。没有定义返回类型的函数会返回特殊的值,叫 <code>Void</code>。它其实是一个空的元组(tuple),没有任何元素,可以写成<code>()</code>。 </p>
</blockquote>
<p>被调用时,一个函数的返回值可以被忽略:</p>
<pre><code class="lang-swift">func printAndCount(stringToPrint: String) -> Int {
println(stringToPrint)
return countElements(stringToPrint)
}
func printWithoutCounting(stringToPrint: String) {
printAndCount(stringToPrint)
}
printAndCount("hello, world")
// prints "hello, world" and returns a value of 12
printWithoutCounting("hello, world")
// prints "hello, world" but does not return a value
</code></pre>
<p>第一个函数 <code>printAndCount</code>,输出一个字符串并返回 <code>Int</code> 类型的字符数。第二个函数 <code>printWithoutCounting</code>调用了第一个函数,但是忽略了它的返回值。当第二个函数被调用时,消息依然会由第一个函数输出,但是返回值不会被用到。</p>
<blockquote>
<p>注意:<br>返回值可以被忽略,但定义了有返回值的函数必须返回一个值,如果在函数定义底部没有返回任何值,这叫导致编译错误(compile-time error)。 </p>
</blockquote>
<h3 id="-functions-with-multiple-return-values-">多重返回值函数(Functions with Multiple Return Values)</h3>
<p>你可以用元组(tuple)类型让多个值作为一个复合值从函数中返回。</p>
<p>下面的这个例子中,<code>count</code> 函数用来计算一个字符串中元音,辅音和其他字母的个数(基于美式英语的标准)。</p>
<pre><code class="lang-swift">func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a", "e", "i", "o", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
}
</code></pre>
<p>你可以用 <code>count</code> 函数来处理任何一个字符串,返回的值将是一个包含三个 <code>Int</code> 型值的元组(tuple):</p>
<pre><code class="lang-swift">let total = count("some arbitrary string!")
println("\(total.vowels) vowels and \(total.consonants) consonants")
// prints "6 vowels and 13 consonants"
</code></pre>
<p>需要注意的是,元组的成员不需要在函数中返回时命名,因为它们的名字已经在函数返回类型有有了定义。</p>
<p><a name="Function_Parameter_Names"></a></p>
<h2 id="-function-parameter-names-">函数参数名称(Function Parameter Names)</h2>
<p>以上所有的函数都给它们的参数定义了<code>参数名(parameter name)</code>:</p>
<pre><code class="lang-swift">func someFunction(parameterName: Int) {
// function body goes here, and can use parameterName
// to refer to the argument value for that parameter
}
</code></pre>
<p>但是,这些参数名仅在函数体中使用,不能在函数调用时使用。这种类型的参数名被称作<code>局部参数名(local parameter name)</code>,因为它们只能在函数体中使用。</p>
<h3 id="-external-parameter-names-">外部参数名(External Parameter Names)</h3>
<p>有时候,调用函数时,给每个参数命名是非常有用的,因为这些参数名可以指出各个实参的用途是什么。</p>
<p>如果你希望函数的使用者在调用函数时提供参数名字,那就需要给每个参数除了局部参数名外再定义一个<code>外部参数名</code>。外部参数名写在局部参数名之前,用空格分隔。</p>
<pre><code class="lang-swift">func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
</code></pre>
<blockquote>
<p>注意:<br>如果你提供了外部参数名,那么函数在被调用时,必须使用外部参数名。 </p>
</blockquote>
<p>以下是个例子,这个函数使用一个<code>结合者(joiner)</code>把两个字符串联在一起:</p>
<pre><code class="lang-swift">func join(s1: String, s2: String, joiner: String) -> String {
return s1 + joiner + s2
}
</code></pre>
<p>当你调用这个函数时,这三个字符串的用途是不清楚的:</p>
<pre><code class="lang-swift">join("hello", "world", ", ")
// returns "hello, world"
</code></pre>
<p>为了让这些字符串的用途更为明显,我们为 <code>join</code> 函数添加外部参数名:</p>
<pre><code class="lang-swift">func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String {
return s1 + joiner + s2
}
</code></pre>
<p>在这个版本的 <code>join</code> 函数中,第一个参数有一个叫 <code>string</code> 的外部参数名和 <code>s1</code> 的局部参数名,第二个参数有一个叫 <code>toString</code> 的外部参数名和 <code>s2</code> 的局部参数名,第三个参数有一个叫 <code>withJoiner</code> 的外部参数名和 <code>joiner</code> 的局部参数名。</p>
<p>现在,你可以使用这些外部参数名以一种清晰地方式来调用函数了:</p>
<pre><code class="lang-swift">join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"
</code></pre>
<p>使用外部参数名让第二个版本的 <code>join</code> 函数的调用更为有表现力,更为通顺,同时还保持了函数体是可读的和有明确意图的。</p>
<blockquote>
<p>注意:<br>当其他人在第一次读你的代码,函数参数的意图显得不明显时,考虑使用外部参数名。如果函数参数名的意图是很明显的,那就不需要定义外部参数名了。 </p>
</blockquote>
<h3 id="-shorthand-external-parameter-names-">简写外部参数名(Shorthand External Parameter Names)</h3>
<p>如果你需要提供外部参数名,但是局部参数名已经定义好了,那么你不需要写两次这些参数名。相反,只写一次参数名,并用<code>井号(#)</code>作为前缀就可以了。这告诉 Swift 使用这个参数名作为局部和外部参数名。</p>
<p>下面这个例子定义了一个叫 <code>containsCharacter</code> 的函数,使用<code>井号(#)</code>的方式定义了外部参数名:</p>
<pre><code class="lang-swift">func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
for character in string {
if character == characterToFind {
return true
}
}
return false
}
</code></pre>
<p>这样定义参数名,使得函数体更为可读,清晰,同时也可以以一个不含糊的方式被调用:</p>
<pre><code class="lang-swift">let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
// containsAVee equals true, because "aardvark" contains a "v”
</code></pre>
<h3 id="-default-parameter-values-">默认参数值(Default Parameter Values)</h3>
<p>你可以在函数体中为每个参数定义<code>默认值</code>。当默认值被定义后,调用这个函数时可以略去这个参数。</p>
<blockquote>
<p>注意:<br>将带有默认值的参数放在函数参数表的最后。这样可以保证在函数调用时,非默认参数的顺序是一致的,同时使得相同的函数在不同情况下调用时显得更为清晰。 </p>
</blockquote>
<p>以下是另一个版本的<code>join</code>函数,其中<code>joiner</code>有了默认参数值:</p>
<pre><code class="lang-swift">func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String {
return s1 + joiner + s2
}
</code></pre>
<p>像第一个版本的 <code>join</code> 函数一样,如果 <code>joiner</code> 被赋值时,函数将使用这个字符串值来连接两个字符串:</p>
<pre><code class="lang-swift">join(string: "hello", toString: "world", withJoiner: "-")
// returns "hello-world"
</code></pre>
<p>当这个函数被调用时,如果 <code>joiner</code> 的值没有被指定,函数会使用默认值(" "):</p>
<pre><code class="lang-swift">join(string: "hello", toString:"world")
// returns "hello world"
</code></pre>
<h3 id="-external-names-for-parameters-with-default-values-">默认值参数的外部参数名(External Names for Parameters with Default Values)</h3>
<p>在大多数情况下,给带默认值的参数起一个外部参数名是很有用的。这样可以保证当函数被调用且带默认值的参数被提供值时,实参的意图是明显的。</p>
<p>为了使定义外部参数名更加简单,当你未给带默认值的参数提供外部参数名时,Swift 会自动提供外部名字。此时外部参数名与局部名字是一样的,就像你已经在局部参数名前写了<code>井号(#)</code>一样。</p>
<p>下面是 <code>join</code> 函数的另一个版本,这个版本中并没有为它的参数提供外部参数名,但是 <code>joiner</code> 参数依然有外部参数名:</p>
<pre><code class="lang-swift">func join(s1: String, s2: String, joiner: String = " ") -> String {
return s1 + joiner + s2
}
</code></pre>
<p>在这个例子中,Swift 自动为 <code>joiner</code> 提供了外部参数名。因此,当函数调用时,外部参数名必须使用,这样使得参数的用途变得清晰。</p>
<pre><code class="lang-swift">join("hello", "world", joiner: "-")
// returns "hello-world"
</code></pre>
<blockquote>
<p>注意:<br>你可以使用<code>下划线(_)</code>作为默认值参数的外部参数名,这样可以在调用时不用提供外部参数名。但是给带默认值的参数命名总是更加合适的。 </p>
</blockquote>
<h3 id="-variadic-parameters-">可变参数(Variadic Parameters)</h3>
<p>一个<code>可变参数(variadic parameter)</code>可以接受一个或多个值。函数调用时,你可以用可变参数来传入不确定数量的输入参数。通过在变量类型名后面加入<code>(...)</code>的方式来定义可变参数。</p>
<p>传入可变参数的值在函数体内当做这个类型的一个数组。例如,一个叫做 <code>numbers</code> 的 <code>Double...</code> 型可变参数,在函数体内可以当做一个叫 <code>numbers</code> 的 <code>Double[]</code> 型的数组常量。</p>
<p>下面的这个函数用来计算一组任意长度数字的算术平均数:</p>
<pre><code class="lang-swift">func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers
</code></pre>
<blockquote>
<p>注意:<br>一个函数至多能有一个可变参数,而且它必须是参数表中最后的一个。这样做是为了避免函数调用时出现歧义。 </p>
</blockquote>
<p>如果函数有一个或多个带默认值的参数,而且还有一个可变参数,那么把可变参数放在参数表的最后。</p>
<h3 id="-constant-and-variable-parameters-">常量参数和变量参数(Constant and Variable Parameters)</h3>
<p>函数参数默认是常量。试图在函数体中更改参数值将会导致编译错误。这意味着你不能错误地更改参数值。</p>
<p>但是,有时候,如果函数中有传入参数的变量值副本将是很有用的。你可以通过指定一个或多个参数为变量参数,从而避免自己在函数中定义新的变量。变量参数不是常量,你可以在函数中把它当做新的可修改副本来使用。</p>
<p>通过在参数名前加关键字 <code>var</code> 来定义变量参数:</p>
<pre><code class="lang-swift">func alignRight(var string: String, count: Int, pad: Character) -> String {
let amountToPad = count - countElements(string)
for _ in 1...amountToPad {
string = pad + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello"
</code></pre>
<p>这个例子中定义了一个新的叫做 <code>alignRight</code> 的函数,用来右对齐输入的字符串到一个长的输出字符串中。左侧空余的地方用指定的填充字符填充。这个例子中,字符串<code>"hello"</code>被转换成了<code>"-----hello"</code>。</p>
<p><code>alignRight</code> 函数将参数 <code>string</code> 定义为变量参数。这意味着 <code>string</code> 现在可以作为一个局部变量,用传入的字符串值初始化,并且可以在函数体中进行操作。</p>
<p>该函数首先计算出多少个字符需要被添加到 <code>string</code> 的左边,以右对齐到总的字符串中。这个值存在局部常量 <code>amountToPad</code> 中。这个函数然后将 <code>amountToPad</code> 多的填充(pad)字符填充到 <code>string</code> 左边,并返回结果。它使用了 <code>string</code> 这个变量参数来进行所有字符串操作。</p>
<blockquote>
<p>注意:<br>对变量参数所进行的修改在函数调用结束后便消失了,并且对于函数体外是不可见的。变量参数仅仅存在于函数调用的生命周期中。 </p>
</blockquote>
<h3 id="-in-out-parameters-">输入输出参数(In-Out Parameters)</h3>
<p>变量参数,正如上面所述,仅仅能在函数体内被更改。如果你想要一个函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数(In-Out Parameters)。</p>
<p>定义一个输入输出参数时,在参数定义前加 <code>inout</code> 关键字。一个输入输出参数有传入函数的值,这个值被函数修改,然后被传出函数,替换原来的值。</p>
<p>你只能传入一个变量作为输入输出参数。你不能传入常量或者字面量(literal value),因为这些量是不能被修改的。当传入的参数作为输入输出参数时,需要在参数前加<code>&</code>符,表示这个值可以被函数修改。</p>
<blockquote>
<p>注意:<br>输入输出参数不能有默认值,而且可变参数不能用 <code>inout</code> 标记。如果你用 <code>inout</code> 标记一个参数,这个参数不能被 <code>var</code> 或者 <code>let</code> 标记。 </p>
</blockquote>
<p>下面是例子,<code>swapTwoInts</code> 函数,有两个分别叫做 <code>a</code> 和 <code>b</code> 的输出输出参数:</p>
<pre><code class="lang-swift">func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
</code></pre>
<p>这个 <code>swapTwoInts</code> 函数仅仅交换 <code>a</code> 与 <code>b</code> 的值。该函数先将 <code>a</code> 的值存到一个暂时常量 <code>temporaryA</code> 中,然后将 <code>b</code> 的值赋给 <code>a</code>,最后将 <code>temporaryA</code> 幅值给 <code>b</code>。</p>
<p>你可以用两个 <code>Int</code> 型的变量来调用 <code>swapTwoInts</code>。需要注意的是,<code>someInt</code> 和 <code>anotherInt</code> 在传入 <code>swapTwoInts</code> 函数前,都加了 <code>&</code> 的前缀:</p>
<pre><code class="lang-swift">var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3”
</code></pre>
<p>从上面这个例子中,我们可以看到 <code>someInt</code> 和 <code>anotherInt</code> 的原始值在 <code>swapTwoInts</code> 函数中被修改,尽管它们的定义在函数体外。</p>
<blockquote>
<p>注意:<br>输出输出参数和返回值是不一样的。上面的 <code>swapTwoInts</code> 函数并没有定义任何返回值,但仍然修改了 <code>someInt</code> 和 <code>anotherInt</code> 的值。输入输出参数是函数对函数体外产生影响的另一种方式。 </p>
</blockquote>
<p><a name="Function_Types"></a></p>
<h2 id="-function-types-">函数类型(Function Types)</h2>
<p>每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成。</p>
<p>例如:</p>
<pre><code class="lang-swift">func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
func multiplyTwoInts(a: Int, b: Int) -> Int {
return a * b
}
</code></pre>
<p>这个例子中定义了两个简单的数学函数:<code>addTwoInts</code> 和 <code>multiplyTwoInts</code>。这两个函数都传入两个 <code>Int</code> 类型, 返回一个合适的<code>Int</code>值。</p>
<p>这两个函数的类型是 <code>(Int, Int) -> Int</code>,可以读作“这个函数类型,它有两个 <code>Int</code> 型的参数并返回一个 <code>Int</code> 型的值。”。</p>
<p>下面是另一个例子,一个没有参数,也没有返回值的函数:</p>
<pre><code class="lang-swift">func printHelloWorld() {
println("hello, world")
}
</code></pre>
<p>这个函数的类型是:<code>() -> ()</code>,或者叫“没有参数,并返回 <code>Void</code> 类型的函数”。没有指定返回类型的函数总返回 <code>Void</code>。在Swift中,<code>Void</code> 与空的元组是一样的。</p>
<h3 id="-using-function-types-">使用函数类型(Using Function Types)</h3>
<p>在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将函数赋值给它:</p>
<pre><code class="lang-swift">var mathFunction: (Int, Int) -> Int = addTwoInts
</code></pre>
<p>这个可以读作:</p>
<p>“定义一个叫做 <code>mathFunction</code> 的变量,类型是‘一个有两个 <code>Int</code> 型的参数并返回一个 <code>Int</code> 型的值的函数’,并让这个新变量指向 <code>addTwoInts</code> 函数”。</p>
<p><code>addTwoInts</code> 和 <code>mathFunction</code> 有同样的类型,所以这个赋值过程在 Swift 类型检查中是允许的。</p>
<p>现在,你可以用 <code>mathFunction</code> 来调用被赋值的函数了:</p>
<pre><code class="lang-swift">println("Result: \(mathFunction(2, 3))")
// prints "Result: 5"
</code></pre>
<p>有相同匹配类型的不同函数可以被赋值给同一个变量,就像非函数类型的变量一样:</p>
<pre><code class="lang-swift">mathFunction = multiplyTwoInts
println("Result: \(mathFunction(2, 3))")
// prints "Result: 6"
</code></pre>
<p>就像其他类型一样,当赋值一个函数给常量或变量时,你可以让 Swift 来推断其函数类型:</p>
<pre><code class="lang-swift">let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int) -> Int
</code></pre>
<h3 id="-function-types-as-parameter-types-">函数类型作为参数类型(Function Types as Parameter Types)</h3>
<p>你可以用<code>(Int, Int) -> Int</code>这样的函数类型作为另一个函数的参数类型。这样你可以将函数的一部分实现交由给函数的调用者。</p>
<p>下面是另一个例子,正如上面的函数一样,同样是输出某种数学运算结果:</p>
<pre><code class="lang-swift">func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8”
</code></pre>
<p>这个例子定义了 <code>printMathResult</code> 函数,它有三个参数:第一个参数叫 <code>mathFunction</code>,类型是<code>(Int, Int) -> Int</code>,你可以传入任何这种类型的函数;第二个和第三个参数叫 <code>a</code> 和 <code>b</code>,它们的类型都是 <code>Int</code>,这两个值作为已给的函数的输入值。</p>
<p>当 <code>printMathResult</code> 被调用时,它被传入 <code>addTwoInts</code> 函数和整数<code>3</code>和<code>5</code>。它用传入<code>3</code>和<code>5</code>调用 <code>addTwoInts</code>,并输出结果:<code>8</code>。</p>
<p><code>printMathResult</code> 函数的作用就是输出另一个合适类型的数学函数的调用结果。它不关心传入函数是如何实现的,它只关心这个传入的函数类型是正确的。这使得 <code>printMathResult</code> 可以以一种类型安全(type-safe)的方式来保证传入函数的调用是正确的。</p>
<h3 id="-function-type-as-return-types-">函数类型作为返回类型(Function Type as Return Types)</h3>
<p>你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头(<code>-></code>)后写一个完整的函数类型。</p>
<p>下面的这个例子中定义了两个简单函数,分别是 <code>stepForward</code> 和<code>stepBackward</code>。<code>stepForward</code> 函数返回一个比输入值大一的值。<code>stepBackward</code> 函数返回一个比输入值小一的值。这两个函数的类型都是 <code>(Int) -> Int</code>:</p>
<pre><code class="lang-swift">func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
</code></pre>
<p>下面这个叫做 <code>chooseStepFunction</code> 的函数,它的返回类型是 <code>(Int) -> Int</code> 的函数。<code>chooseStepFunction</code> 根据布尔值 <code>backwards</code> 来返回 <code>stepForward</code> 函数或 <code>stepBackward</code> 函数:</p>
<pre><code class="lang-swift">func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
</code></pre>
<p>你现在可以用 <code>chooseStepFunction</code> 来获得一个函数,不管是那个方向:</p>
<pre><code class="lang-swift">var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function
</code></pre>
<p>上面这个例子中计算出从 <code>currentValue</code> 逐渐接近到<code>0</code>是需要向正数走还是向负数走。<code>currentValue</code> 的初始值是<code>3</code>,这意味着 <code>currentValue > 0</code> 是真的(<code>true</code>),这将使得 <code>chooseStepFunction</code> 返回 <code>stepBackward</code> 函数。一个指向返回的函数的引用保存在了 <code>moveNearerToZero</code> 常量中。</p>
<p>现在,<code>moveNearerToZero</code> 指向了正确的函数,它可以被用来数到<code>0</code>:</p>
<pre><code class="lang-swift">println("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// 3...
// 2...
// 1...
// zero!
</code></pre>
<p><a name="Nested_Functions"></a></p>
<h2 id="-nested-functions-">嵌套函数(Nested Functions)</h2>
<p>这章中你所见到的所有函数都叫全局函数(global functions),它们定义在全局域中。你也可以把函数定义在别的函数体中,称作嵌套函数(nested functions)。</p>
<p>默认情况下,嵌套函数是对外界不可见的,但是可以被他们封闭函数(enclosing function)来调用。一个封闭函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用。</p>
<p>你可以用返回嵌套函数的方式重写 <code>chooseStepFunction</code> 函数:</p>
<pre><code class="lang-swift">func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
</code></pre>
</section>
</div>
</div>
</div>
<a href="../chapter2/05_Control_Flow.html" class="navigation navigation-prev " aria-label="Previous page: 控制流"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/07_Closures.html" class="navigation navigation-next " aria-label="Next page: 闭包"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.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>