-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14_Initialization.html
1066 lines (777 loc) · 63.5 KB
/
14_Initialization.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/15_Deinitialization.html" />
<link rel="prev" href="../chapter2/13_Inheritance.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.14" 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: 26.31578947368421%;min-width: 23.68421052631579%;"></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 " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="类型嵌套" class="chapter " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter " 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_116">
<blockquote>
<p>翻译:lifedim</p>
<p>校对:lifedim</p>
</blockquote>
<h1 id="-initialization-">构造过程(Initialization)</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li><a href="#setting_initial_values_for_stored_properties">存储型属性的初始赋值</a></li>
<li><a href="#customizing_initialization">定制化构造过程</a></li>
<li><a href="#default_initializers">默认构造器</a></li>
<li><a href="#initializer_delegation_for_value_types">值类型的构造器代理</a></li>
<li><a href="#class_inheritance_and_initialization">类的继承和构造过程</a></li>
<li><a href="#setting_a_default_property_value_with_a_closure_or_function">通过闭包和函数来设置属性的默认值</a></li>
</ul>
<p>构造过程是为了使用某个类、结构体或枚举类型的实例而进行的准备过程。这个过程包含了为实例中的每个属性设置初始值和为其执行必要的准备和初始化任务。</p>
<p>构造过程是通过定义构造器(<code>Initializers</code>)来实现的,这些构造器可以看做是用来创建特定类型实例的特殊方法。与 Objective-C 中的构造器不同,Swift 的构造器无需返回值,它们的主要任务是保证新实例在第一次使用前完成正确的初始化。</p>
<p>类实例也可以通过定义析构器(<code>deinitializer</code>)在类实例释放之前执行特定的清除工作。想了解更多关于析构器的内容,请参考<a href="../chapter2/15_Deinitialization.html">析构过程</a>。</p>
<p><a name="setting_initial_values_for_stored_properties"></a></p>
<h2 id="-">存储型属性的初始赋值</h2>
<p>类和结构体在实例创建时,必须为所有存储型属性设置合适的初始值。存储型属性的值不能处于一个未知的状态。</p>
<p>你可以在构造器中为存储型属性赋初值,也可以在定义属性时为其设置默认值。以下章节将详细介绍这两种方法。</p>
<blockquote>
<p>注意:</p>
<p>当你为存储型属性设置默认值或者在构造器中为其赋值时,它们的值是被直接设置的,不会触发任何属性观测器(<code>property observers</code>)。</p>
</blockquote>
<h3 id="-">构造器</h3>
<p>构造器在创建某特定类型的新实例时调用。它的最简形式类似于一个不带任何参数的实例方法,以关键字<code>init</code>命名。</p>
<p>下面例子中定义了一个用来保存华氏温度的结构体<code>Fahrenheit</code>,它拥有一个<code>Double</code>类型的存储型属性<code>temperature</code>:</p>
<pre><code>struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
println("The default temperature is \(f.temperature)° Fahrenheit")
// 输出 "The default temperature is 32.0° Fahrenheit”
</code></pre><p>这个结构体定义了一个不带参数的构造器<code>init</code>,并在里面将存储型属性<code>temperature</code>的值初始化为<code>32.0</code>(华摄氏度下水的冰点)。</p>
<h3 id="-">默认属性值</h3>
<p>如前所述,你可以在构造器中为存储型属性设置初始值;同样,你也可以在属性声明时为其设置默认值。</p>
<blockquote>
<p>注意:</p>
<p>如果一个属性总是使用同一个初始值,可以为其设置一个默认值。无论定义默认值还是在构造器中赋值,最终它们实现的效果是一样的,只不过默认值跟属性构造过程结合的更紧密。使用默认值能让你的构造器更简洁、更清晰,且能通过默认值自动推导出属性的类型;同时,它也能让你充分利用默认构造器、构造器继承(后续章节将讲到)等特性。</p>
</blockquote>
<p>你可以使用更简单的方式在定义结构体<code>Fahrenheit</code>时为属性<code>temperature</code>设置默认值:</p>
<pre><code>struct Fahrenheit {
var temperature = 32.0
}
</code></pre><p><a name="customizing_initialization"></a></p>
<h2 id="-">定制化构造过程</h2>
<p>你可以通过输入参数和可选属性类型来定制构造过程,也可以在构造过程中修改常量属性。这些都将在后面章节中提到。</p>
<h3 id="-">构造参数</h3>
<p>你可以在定义构造器时提供构造参数,为其提供定制化构造所需值的类型和名字。构造器参数的功能和语法跟函数和方法参数相同。</p>
<p>下面例子中定义了一个包含摄氏度温度的结构体<code>Celsius</code>。它定义了两个不同的构造器:<code>init(fromFahrenheit:)</code>和<code>init(fromKelvin:)</code>,二者分别通过接受不同刻度表示的温度值来创建新的实例:</p>
<pre><code>struct Celsius {
var temperatureInCelsius: Double = 0.0
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius 是 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius 是 0.0”
</code></pre><p>第一个构造器拥有一个构造参数,其外部名字为<code>fromFahrenheit</code>,内部名字为<code>fahrenheit</code>;第二个构造器也拥有一个构造参数,其外部名字为<code>fromKelvin</code>,内部名字为<code>kelvin</code>。这两个构造器都将唯一的参数值转换成摄氏温度值,并保存在属性<code>temperatureInCelsius</code>中。</p>
<h3 id="-">内部和外部参数名</h3>
<p>跟函数和方法参数相同,构造参数也存在一个在构造器内部使用的参数名字和一个在调用构造器时使用的外部参数名字。</p>
<p>然而,构造器并不像函数和方法那样在括号前有一个可辨别的名字。所以在调用构造器时,主要通过构造器中的参数名和类型来确定需要调用的构造器。正因为参数如此重要,如果你在定义构造器时没有提供参数的外部名字,Swift 会为每个构造器的参数自动生成一个跟内部名字相同的外部名,就相当于在每个构造参数之前加了一个哈希符号。</p>
<blockquote>
<p>注意:</p>
<p>如果你不希望为构造器的某个参数提供外部名字,你可以使用下划线<code>_</code>来显示描述它的外部名,以此覆盖上面所说的默认行为。</p>
</blockquote>
<p>以下例子中定义了一个结构体<code>Color</code>,它包含了三个常量:<code>red</code>、<code>green</code>和<code>blue</code>。这些属性可以存储0.0到1.0之间的值,用来指示颜色中红、绿、蓝成分的含量。</p>
<p><code>Color</code>提供了一个构造器,其中包含三个<code>Double</code>类型的构造参数:</p>
<pre><code>struct Color {
let red = 0.0, green = 0.0, blue = 0.0
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
}
</code></pre><p>每当你创建一个新的<code>Color</code>实例,你都需要通过三种颜色的外部参数名来传值,并调用构造器。</p>
<pre><code>let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
</code></pre><p>注意,如果不通过外部参数名字传值,你是没法调用这个构造器的。只要构造器定义了某个外部参数名,你就必须使用它,忽略它将导致编译错误:</p>
<pre><code>let veryGreen = Color(0.0, 1.0, 0.0)
// 报编译时错误,需要外部名称
</code></pre><h3 id="-">可选属性类型</h3>
<p>如果你定制的类型包含一个逻辑上允许取值为空的存储型属性--不管是因为它无法在初始化时赋值,还是因为它可以在之后某个时间点可以赋值为空--你都需要将它定义为可选类型<code>optional type</code>。可选类型的属性将自动初始化为空<code>nil</code>,表示这个属性是故意在初始化时设置为空的。</p>
<p>下面例子中定义了类<code>SurveyQuestion</code>,它包含一个可选字符串属性<code>response</code>:</p>
<pre><code>class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
println(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// 输出 "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese.
</code></pre><p>调查问题在问题提出之后,我们才能得到回答。所以我们将属性回答<code>response</code>声明为<code>String?</code>类型,或者说是可选字符串类型<code>optional String</code>。当<code>SurveyQuestion</code>实例化时,它将自动赋值为空<code>nil</code>,表明暂时还不存在此字符串。</p>
<h3 id="-">构造过程中常量属性的修改</h3>
<p>只要在构造过程结束前常量的值能确定,你可以在构造过程中的任意时间点修改常量属性的值。</p>
<blockquote>
<p>注意:</p>
<p>对某个类实例来说,它的常量属性只能在定义它的类的构造过程中修改;不能在子类中修改。</p>
</blockquote>
<p>你可以修改上面的<code>SurveyQuestion</code>示例,用常量属性替代变量属性<code>text</code>,指明问题内容<code>text</code>在其创建之后不会再被修改。尽管<code>text</code>属性现在是常量,我们仍然可以在其类的构造器中修改它的值:</p>
<pre><code>class SurveyQuestion {
let text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
println(text)
}
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
beetsQuestion.ask()
// 输出 "How about beets?"
beetsQuestion.response = "I also like beets. (But not with cheese.)
</code></pre><p><a name="default_initializers"></a></p>
<h2 id="-">默认构造器</h2>
<p>Swift 将为所有属性已提供默认值的且自身没有定义任何构造器的结构体或基类,提供一个默认的构造器。这个默认构造器将简单的创建一个所有属性值都设置为默认值的实例。</p>
<p>下面例子中创建了一个类<code>ShoppingListItem</code>,它封装了购物清单中的某一项的属性:名字(<code>name</code>)、数量(<code>quantity</code>)和购买状态 <code>purchase state</code>。</p>
<pre><code>class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
</code></pre><p>由于<code>ShoppingListItem</code>类中的所有属性都有默认值,且它是没有父类的基类,它将自动获得一个可以为所有属性设置默认值的默认构造器(尽管代码中没有显式为<code>name</code>属性设置默认值,但由于<code>name</code>是可选字符串类型,它将默认设置为<code>nil</code>)。上面例子中使用默认构造器创造了一个<code>ShoppingListItem</code>类的实例(使用<code>ShoppingListItem()</code>形式的构造器语法),并将其赋值给变量<code>item</code>。</p>
<h3 id="-">结构体的逐一成员构造器</h3>
<p>除上面提到的默认构造器,如果结构体对所有存储型属性提供了默认值且自身没有提供定制的构造器,它们能自动获得一个逐一成员构造器。</p>
<p>逐一成员构造器是用来初始化结构体新实例里成员属性的快捷方法。我们在调用逐一成员构造器时,通过与成员属性名相同的参数名进行传值来完成对成员属性的初始赋值。</p>
<p>下面例子中定义了一个结构体<code>Size</code>,它包含两个属性<code>width</code>和<code>height</code>。Swift 可以根据这两个属性的初始赋值<code>0.0</code>自动推导出它们的类型<code>Double</code>。</p>
<p>由于这两个存储型属性都有默认值,结构体<code>Size</code>自动获得了一个逐一成员构造器 <code>init(width:height:)</code>。 你可以用它来为<code>Size</code>创建新的实例:</p>
<pre><code>struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
</code></pre><p><a name="initializer_delegation_for_value_types"></a></p>
<h2 id="-">值类型的构造器代理</h2>
<p>构造器可以通过调用其它构造器来完成实例的部分构造过程。这一过程称为构造器代理,它能减少多个构造器间的代码重复。</p>
<p>构造器代理的实现规则和形式在值类型和类类型中有所不同。值类型(结构体和枚举类型)不支持继承,所以构造器代理的过程相对简单,因为它们只能代理任务给本身提供的其它构造器。类则不同,它可以继承自其它类(请参考<a href="../chapter2/13_Inheritance.html">继承</a>),这意味着类有责任保证其所有继承的存储型属性在构造时也能正确的初始化。这些责任将在后续章节<a href="#class_inheritance_and_initialization">类的继承和构造过程</a>中介绍。</p>
<p>对于值类型,你可以使用<code>self.init</code>在自定义的构造器中引用其它的属于相同值类型的构造器。并且你只能在构造器内部调用<code>self.init</code>。</p>
<p>注意,如果你为某个值类型定义了一个定制的构造器,你将无法访问到默认构造器(如果是结构体,则无法访问逐一对象构造器)。这个限制可以防止你在为值类型定义了一个更复杂的,完成了重要准备构造器之后,别人还是错误的使用了那个自动生成的构造器。</p>
<blockquote>
<p>注意:</p>
<p>假如你想通过默认构造器、逐一对象构造器以及你自己定制的构造器为值类型创建实例,我们建议你将自己定制的构造器写到扩展(<code>extension</code>)中,而不是跟值类型定义混在一起。想查看更多内容,请查看<a href="../chapter2/20_Extensions.html">扩展</a>章节。</p>
</blockquote>
<p>下面例子将定义一个结构体<code>Rect</code>,用来展现几何矩形。这个例子需要两个辅助的结构体<code>Size</code>和<code>Point</code>,它们各自为其所有的属性提供了初始值<code>0.0</code>。</p>
<pre><code>struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
</code></pre><p>你可以通过以下三种方式为<code>Rect</code>创建实例--使用默认的0值来初始化<code>origin</code>和<code>size</code>属性;使用特定的<code>origin</code>和<code>size</code>实例来初始化;使用特定的<code>center</code>和<code>size</code>来初始化。在下面<code>Rect</code>结构体定义中,我们为着三种方式提供了三个自定义的构造器:</p>
<pre><code>struct Rect {
var origin = Point()
var size = Size()
init() {}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
</code></pre><p>第一个<code>Rect</code>构造器<code>init()</code>,在功能上跟没有自定义构造器时自动获得的默认构造器是一样的。这个构造器是一个空函数,使用一对大括号<code>{}</code>来描述,它没有执行任何定制的构造过程。调用这个构造器将返回一个<code>Rect</code>实例,它的<code>origin</code>和<code>size</code>属性都使用定义时的默认值<code>Point(x: 0.0, y: 0.0)</code>和<code>Size(width: 0.0, height: 0.0)</code>:</p>
<pre><code>let basicRect = Rect()
// basicRect 的原点是 (0.0, 0.0),尺寸是 (0.0, 0.0)
</code></pre><p>第二个<code>Rect</code>构造器<code>init(origin:size:)</code>,在功能上跟结构体在没有自定义构造器时获得的逐一成员构造器是一样的。这个构造器只是简单的将<code>origin</code>和<code>size</code>的参数值赋给对应的存储型属性:</p>
<pre><code>let originRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
// originRect 的原点是 (2.0, 2.0),尺寸是 (5.0, 5.0)
</code></pre><p>第三个<code>Rect</code>构造器<code>init(center:size:)</code>稍微复杂一点。它先通过<code>center</code>和<code>size</code>的值计算出<code>origin</code>的坐标。然后再调用(或代理给)<code>init(origin:size:)</code>构造器来将新的<code>origin</code>和<code>size</code>值赋值到对应的属性中:</p>
<p>let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect 的原点是 (2.5, 2.5),尺寸是 (3.0, 3.0)</p>
<p>构造器<code>init(center:size:)</code>可以自己将<code>origin</code>和<code>size</code>的新值赋值到对应的属性中。然而尽量利用现有的构造器和它所提供的功能来实现<code>init(center:size:)</code>的功能,是更方便、更清晰和更直观的方法。</p>
<blockquote>
<p>注意:</p>
<p>如果你想用另外一种不需要自己定义<code>init()</code>和<code>init(origin:size:)</code>的方式来实现这个例子,请参考<a href="../chapter2/20_Extensions.html">扩展</a>。</p>
</blockquote>
<p><a name="class_inheritance_and_initialization"></a></p>
<h2 id="-">类的继承和构造过程</h2>
<p>类里面的所有存储型属性--包括所有继承自父类的属性--都必须在构造过程中设置初始值。</p>
<p>Swift 提供了两种类型的类构造器来确保所有类实例中存储型属性都能获得初始值,它们分别是指定构造器和便利构造器。</p>
<h3 id="-">指定构造器和便利构造器</h3>
<p>指定构造器是类中最主要的构造器。一个指定构造器将初始化类中提供的所有属性,并根据父类链往上调用父类的构造器来实现父类的初始化。</p>
<p>每一个类都必须拥有至少一个指定构造器。在某些情况下,许多类通过继承了父类中的指定构造器而满足了这个条件。具体内容请参考后续章节<a href="#automatic_initializer_inheritance">自动构造器的继承</a>。</p>
<p>便利构造器是类中比较次要的、辅助型的构造器。你可以定义便利构造器来调用同一个类中的指定构造器,并为其参数提供默认值。你也可以定义便利构造器来创建一个特殊用途或特定输入的实例。</p>
<p>你应当只在必要的时候为类提供便利构造器,比方说某种情况下通过使用便利构造器来快捷调用某个指定构造器,能够节省更多开发时间并让类的构造过程更清、晰明。</p>
<p><a name="initialization_chain"></a></p>
<h3 id="-">构造器链</h3>
<p>为了简化指定构造器和便利构造器之间的调用关系,Swift 采用以下三条规则来限制构造器之间的代理调用:</p>
<h4 id="-1">规则 1</h4>
<p>指定构造器必须调用其直接父类的的指定构造器。</p>
<h4 id="-2">规则 2</h4>
<p>便利构造器必须调用同一类中定义的其它构造器。</p>
<h4 id="-3">规则 3</h4>
<p>便利构造器必须最终以调用一个指定构造器结束。</p>
<p>一个更方便记忆的方法是:</p>
<ul>
<li>指定构造器必须总是向上代理</li>
<li>便利构造器必须总是横向代理</li>
</ul>
<p>这些规则可以通过下面图例来说明:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/initializerDelegation01_2x.png" alt="构造器代理图"></p>
<p>如图所示,父类中包含一个指定构造器和两个便利构造器。其中一个便利构造器调用了另外一个便利构造器,而后者又调用了唯一的指定构造器。这满足了上面提到的规则2和3。这个父类没有自己的父类,所以规则1没有用到。</p>
<p>子类中包含两个指定构造器和一个便利构造器。便利构造器必须调用两个指定构造器中的任意一个,因为它只能调用同一个类里的其他构造器。这满足了上面提到的规则2和3。而两个指定构造器必须调用父类中唯一的指定构造器,这满足了规则1。</p>
<blockquote>
<p>注意:</p>
<p>这些规则不会影响使用时,如何用类去创建实例。任何上图中展示的构造器都可以用来完整创建对应类的实例。这些规则只在实现类的定义时有影响。</p>
</blockquote>
<p>下面图例中展示了一种更复杂的类层级结构。它演示了指定构造器是如果在类层级中充当“管道”的作用,在类的构造器链上简化了类之间的内部关系。</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/initializerDelegation02_2x.png" alt="复杂构造器代理图"></p>
<p><a name="two_phase_initialization"></a></p>
<h3 id="-">两段式构造过程</h3>
<p>Swift 中类的构造过程包含两个阶段。第一个阶段,每个存储型属性通过引入它们的类的构造器来设置初始值。当每一个存储型属性值被确定后,第二阶段开始,它给每个类一次机会在新实例准备使用之前进一步定制它们的存储型属性。</p>
<p>两段式构造过程的使用让构造过程更安全,同时在整个类层级结构中给予了每个类完全的灵活性。两段式构造过程可以防止属性值在初始化之前被访问;也可以防止属性被另外一个构造器意外地赋予不同的值。</p>
<blockquote>
<p>注意:</p>
<p>Swift的两段式构造过程跟 Objective-C 中的构造过程类似。最主要的区别在于阶段 1,Objective-C 给每一个属性赋值<code>0</code>或空值(比如说<code>0</code>或<code>nil</code>)。Swift 的构造流程则更加灵活,它允许你设置定制的初始值,并自如应对某些属性不能以<code>0</code>或<code>nil</code>作为合法默认值的情况。</p>
</blockquote>
<p>Swift 编译器将执行 4 种有效的安全检查,以确保两段式构造过程能顺利完成:</p>
<h4 id="-1">安全检查 1</h4>
<p>指定构造器必须保证它所在类引入的所有属性都必须先初始化完成,之后才能将其它构造任务向上代理给父类中的构造器。</p>
<p>如上所述,一个对象的内存只有在其所有存储型属性确定之后才能完全初始化。为了满足这一规则,指定构造器必须保证它所在类引入的属性在它往上代理之前先完成初始化。</p>
<h4 id="-2">安全检查 2</h4>
<p>指定构造器必须先向上代理调用父类构造器,然后再为继承的属性设置新值。如果没这么做,指定构造器赋予的新值将被父类中的构造器所覆盖。</p>
<h4 id="-3">安全检查 3</h4>
<p>便利构造器必须先代理调用同一类中的其它构造器,然后再为任意属性赋新值。如果没这么做,便利构造器赋予的新值将被同一类中其它指定构造器所覆盖。</p>
<h4 id="-4">安全检查 4</h4>
<p>构造器在第一阶段构造完成之前,不能调用任何实例方法、不能读取任何实例属性的值,也不能引用<code>self</code>的值。</p>
<p>以下是两段式构造过程中基于上述安全检查的构造流程展示:</p>
<h4 id="-1">阶段 1</h4>
<ul>
<li>某个指定构造器或便利构造器被调用;</li>
<li>完成新实例内存的分配,但此时内存还没有被初始化;</li>
<li>指定构造器确保其所在类引入的所有存储型属性都已赋初值。存储型属性所属的内存完成初始化;</li>
<li>指定构造器将调用父类的构造器,完成父类属性的初始化;</li>
<li>这个调用父类构造器的过程沿着构造器链一直往上执行,直到到达构造器链的最顶部;</li>
<li>当到达了构造器链最顶部,且已确保所有实例包含的存储型属性都已经赋值,这个实例的内存被认为已经完全初始化。此时阶段1完成。</li>
</ul>
<h4 id="-2">阶段 2</h4>
<ul>
<li>从顶部构造器链一直往下,每个构造器链中类的指定构造器都有机会进一步定制实例。构造器此时可以访问<code>self</code>、修改它的属性并调用实例方法等等。</li>
<li>最终,任意构造器链中的便利构造器可以有机会定制实例和使用<code>self</code>。</li>
</ul>
<p>下图展示了在假定的子类和父类之间构造的阶段1:
·
<img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/twoPhaseInitialization01_2x.png" alt="构造过程阶段1"></p>
<p>在这个例子中,构造过程从对子类中一个便利构造器的调用开始。这个便利构造器此时没法修改任何属性,它把构造任务代理给同一类中的指定构造器。</p>
<p>如安全检查1所示,指定构造器将确保所有子类的属性都有值。然后它将调用父类的指定构造器,并沿着造器链一直往上完成父类的构建过程。</p>
<p>父类中的指定构造器确保所有父类的属性都有值。由于没有更多的父类需要构建,也就无需继续向上做构建代理。</p>
<p>一旦父类中所有属性都有了初始值,实例的内存被认为是完全初始化,而阶段1也已完成。</p>
<p>以下展示了相同构造过程的阶段2:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/twoPhaseInitialization02_2x.png" alt="构建过程阶段2"></p>
<p>父类中的指定构造器现在有机会进一步来定制实例(尽管它没有这种必要)。</p>
<p>一旦父类中的指定构造器完成调用,子类的构指定构造器可以执行更多的定制操作(同样,它也没有这种必要)。</p>
<p>最终,一旦子类的指定构造器完成调用,最开始被调用的便利构造器可以执行更多的定制操作。</p>
<h3 id="-">构造器的继承和重载</h3>
<p>跟 Objective-C 中的子类不同,Swift 中的子类不会默认继承父类的构造器。Swift 的这种机制可以防止一个父类的简单构造器被一个更专业的子类继承,并被错误的用来创建子类的实例。</p>
<p>假如你希望自定义的子类中能实现一个或多个跟父类相同的构造器--也许是为了完成一些定制的构造过程--你可以在你定制的子类中提供和重载与父类相同的构造器。</p>
<p>如果你重载的构造器是一个指定构造器,你可以在子类里重载它的实现,并在自定义版本的构造器中调用父类版本的构造器。</p>
<p>如果你重载的构造器是一个便利构造器,你的重载过程必须通过调用同一类中提供的其它指定构造器来实现。这一规则的详细内容请参考<a href="#initialization_chain">构造器链</a>。</p>
<blockquote>
<p>注意:</p>
<p>与方法、属性和下标不同,在重载构造器时你没有必要使用关键字<code>override</code>。</p>
</blockquote>
<p><a name="automatic_initializer_inheritance"></a></p>
<h3 id="-">自动构造器的继承</h3>
<p>如上所述,子类不会默认继承父类的构造器。但是如果特定条件可以满足,父类构造器是可以被自动继承的。在实践中,这意味着对于许多常见场景你不必重载父类的构造器,并且在尽可能安全的情况下以最小的代价来继承父类的构造器。</p>
<p>假设要为子类中引入的任意新属性提供默认值,请遵守以下2个规则:</p>
<h4 id="-1">规则 1</h4>
<p>如果子类没有定义任何指定构造器,它将自动继承所有父类的指定构造器。</p>
<h4 id="-2">规则 2</h4>
<p>如果子类提供了所有父类指定构造器的实现--不管是通过规则1继承过来的,还是通过自定义实现的--它将自动继承所有父类的便利构造器。</p>
<p>即使你在子类中添加了更多的便利构造器,这两条规则仍然适用。</p>
<blockquote>
<p>注意:</p>
<p>子类可以通过部分满足规则2的方式,使用子类便利构造器来实现父类的指定构造器。</p>
</blockquote>
<h3 id="-">指定构造器和便利构造器的语法</h3>
<p>类的指定构造器的写法跟值类型简单构造器一样:</p>
<pre><code>init(parameters) {
statements
}
</code></pre><p>便利构造器也采用相同样式的写法,但需要在<code>init</code>关键字之前放置<code>convenience</code>关键字,并使用空格将它们俩分开:</p>
<pre><code>convenience init(parameters) {
statements
}
</code></pre><h3 id="-">指定构造器和便利构造器实战</h3>
<p>接下来的例子将在实战中展示指定构造器、便利构造器和自动构造器的继承。它定义了包含三个类<code>Food</code>、<code>RecipeIngredient</code>以及<code>ShoppingListItem</code>的类层次结构,并将演示它们的构造器是如何相互作用的。</p>
<p>类层次中的基类是<code>Food</code>,它是一个简单的用来封装食物名字的类。<code>Food</code>类引入了一个叫做<code>name</code>的<code>String</code>类型属性,并且提供了两个构造器来创建<code>Food</code>实例:</p>
<pre><code>class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
</code></pre><p>下图中展示了<code>Food</code>的构造器链:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/initializersExample01_2x.png" alt="Food构造器链"></p>
<p>类没有提供一个默认的逐一成员构造器,所以<code>Food</code>类提供了一个接受单一参数<code>name</code>的指定构造器。这个构造器可以使用一个特定的名字来创建新的<code>Food</code>实例:</p>
<pre><code>let namedMeat = Food(name: "Bacon")
// namedMeat 的名字是 "Bacon”
</code></pre><p><code>Food</code>类中的构造器<code>init(name: String)</code>被定义为一个指定构造器,因为它能确保所有新<code>Food</code>实例的中存储型属性都被初始化。<code>Food</code>类没有父类,所以<code>init(name: String)</code>构造器不需要调用<code>super.init()</code>来完成构造。</p>
<p><code>Food</code>类同样提供了一个没有参数的便利构造器 <code>init()</code>。这个<code>init()</code>构造器为新食物提供了一个默认的占位名字,通过代理调用同一类中定义的指定构造器<code>init(name: String)</code>并给参数<code>name</code>传值<code>[Unnamed]</code>来实现:</p>
<pre><code>let mysteryMeat = Food()
// mysteryMeat 的名字是 [Unnamed]
</code></pre><p>类层级中的第二个类是<code>Food</code>的子类<code>RecipeIngredient</code>。<code>RecipeIngredient</code>类构建了食谱中的一味调味剂。它引入了<code>Int</code>类型的数量属性<code>quantity</code>(以及从<code>Food</code>继承过来的<code>name</code>属性),并且定义了两个构造器来创建<code>RecipeIngredient</code>实例:</p>
<pre><code>class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
</code></pre><p>下图中展示了<code>RecipeIngredient</code>类的构造器链:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/initializersExample02_2x.png" alt="RecipeIngredient构造器"></p>
<p><code>RecipeIngredient</code>类拥有一个指定构造器<code>init(name: String, quantity: Int)</code>,它可以用来产生新<code>RecipeIngredient</code>实例的所有属性值。这个构造器一开始先将传入的<code>quantity</code>参数赋值给<code>quantity</code>属性,这个属性也是唯一在<code>RecipeIngredient</code>中新引入的属性。随后,构造器将任务向上代理给父类<code>Food</code>的<code>init(name: String)</code>。这个过程满足<a href="#two_phase_initialization">两段式构造过程</a>中的安全检查1。</p>
<p><code>RecipeIngredient</code>也定义了一个便利构造器<code>init(name: String)</code>,它只通过<code>name</code>来创建<code>RecipeIngredient</code>的实例。这个便利构造器假设任意<code>RecipeIngredient</code>实例的<code>quantity</code>为1,所以不需要显示指明数量即可创建出实例。这个便利构造器的定义可以让创建实例更加方便和快捷,并且避免了使用重复的代码来创建多个<code>quantity</code>为 1 的<code>RecipeIngredient</code>实例。这个便利构造器只是简单的将任务代理给了同一类里提供的指定构造器。</p>
<p>注意,<code>RecipeIngredient</code>的便利构造器<code>init(name: String)</code>使用了跟<code>Food</code>中指定构造器<code>init(name: String)</code>相同的参数。尽管<code>RecipeIngredient</code>这个构造器是便利构造器,<code>RecipeIngredient</code>依然提供了对所有父类指定构造器的实现。因此,<code>RecipeIngredient</code>也能自动继承了所有父类的便利构造器。</p>
<p>在这个例子中,<code>RecipeIngredient</code>的父类是<code>Food</code>,它有一个便利构造器<code>init()</code>。这个构造器因此也被<code>RecipeIngredient</code>继承。这个继承的<code>init()</code>函数版本跟<code>Food</code>提供的版本是一样的,除了它是将任务代理给<code>RecipeIngredient</code>版本的<code>init(name: String)</code>而不是<code>Food</code>提供的版本。</p>
<p>所有的这三种构造器都可以用来创建新的<code>RecipeIngredient</code>实例:</p>
<pre><code>let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
</code></pre><p>类层级中第三个也是最后一个类是<code>RecipeIngredient</code>的子类,叫做<code>ShoppingListItem</code>。这个类构建了购物单中出现的某一种调味料。</p>
<p>购物单中的每一项总是从<code>unpurchased</code>未购买状态开始的。为了展现这一事实,<code>ShoppingListItem</code>引入了一个布尔类型的属性<code>purchased</code>,它的默认值是<code>false</code>。<code>ShoppingListItem</code>还添加了一个计算型属性<code>description</code>,它提供了关于<code>ShoppingListItem</code>实例的一些文字描述:</p>
<pre><code>class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name.lowercaseString)"
output += purchased ? " ✔" : " ✘"
return output
}
}
</code></pre><blockquote>
<p>注意:</p>
<p><code>ShoppingListItem</code>没有定义构造器来为<code>purchased</code>提供初始化值,这是因为任何添加到购物单的项的初始状态总是未购买。</p>
</blockquote>
<p>由于它为自己引入的所有属性都提供了默认值,并且自己没有定义任何构造器,<code>ShoppingListItem</code>将自动继承所有父类中的指定构造器和便利构造器。</p>
<p>下图种展示了所有三个类的构造器链:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/initializersExample03_2x.png" alt="三类构造器图"></p>
<p>你可以使用全部三个继承来的构造器来创建<code>ShoppingListItem</code>的新实例:</p>
<pre><code>var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
println(item.description)
}
// 1 x orange juice ✔
// 1 x bacon ✘
// 6 x eggs ✘
</code></pre><p>如上所述,例子中通过字面量方式创建了一个新数组<code>breakfastList</code>,它包含了三个新的<code>ShoppingListItem</code>实例,因此数组的类型也能自动推导为<code>ShoppingListItem[]</code>。在数组创建完之后,数组中第一个<code>ShoppingListItem</code>实例的名字从<code>[Unnamed]</code>修改为<code>Orange juice</code>,并标记为已购买。接下来通过遍历数组每个元素并打印它们的描述值,展示了所有项当前的默认状态都已按照预期完成了赋值。</p>
<p><a name="setting_a_default_property_value_with_a_closure_or_function"></a></p>
<h2 id="-">通过闭包和函数来设置属性的默认值</h2>
<p>如果某个存储型属性的默认值需要特别的定制或准备,你就可以使用闭包或全局函数来为其属性提供定制的默认值。每当某个属性所属的新类型实例创建时,对应的闭包或函数会被调用,而它们的返回值会当做默认值赋值给这个属性。</p>
<p>这种类型的闭包或函数一般会创建一个跟属性类型相同的临时变量,然后修改它的值以满足预期的初始状态,最后将这个临时变量的值作为属性的默认值进行返回。</p>
<p>下面列举了闭包如何提供默认值的代码概要:</p>
<pre><code>class SomeClass {
let someProperty: SomeType = {
// 在这个闭包中给 someProperty 创建一个默认值
// someValue 必须和 SomeType 类型相同
return someValue
}()
}
</code></pre><p>注意闭包结尾的大括号后面接了一对空的小括号。这是用来告诉 Swift 需要立刻执行此闭包。如果你忽略了这对括号,相当于是将闭包本身作为值赋值给了属性,而不是将闭包的返回值赋值给属性。</p>
<blockquote>
<p>注意:</p>
<p>如果你使用闭包来初始化属性的值,请记住在闭包执行时,实例的其它部分都还没有初始化。这意味着你不能够在闭包里访问其它的属性,就算这个属性有默认值也不允许。同样,你也不能使用隐式的<code>self</code>属性,或者调用其它的实例方法。</p>
</blockquote>
<p>下面例子中定义了一个结构体<code>Checkerboard</code>,它构建了西洋跳棋游戏的棋盘:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Art/checkersBoard_2x.png" alt="西洋跳棋棋盘"></p>
<p>西洋跳棋游戏在一副黑白格交替的 10x10 的棋盘中进行。为了呈现这副游戏棋盘,<code>Checkerboard</code>结构体定义了一个属性<code>boardColors</code>,它是一个包含 100 个布尔值的数组。数组中的某元素布尔值为<code>true</code>表示对应的是一个黑格,布尔值为<code>false</code>表示对应的是一个白格。数组中第一个元素代表棋盘上左上角的格子,最后一个元素代表棋盘上右下角的格子。</p>
<p><code>boardColor</code>数组是通过一个闭包来初始化和组装颜色值的:</p>
<pre><code>struct Checkerboard {
let boardColors: Bool[] = {
var temporaryBoard = Bool[]()
var isBlack = false
for i in 1...10 {