-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInitialization.html
More file actions
1227 lines (1043 loc) · 89.5 KB
/
Initialization.html
File metadata and controls
1227 lines (1043 loc) · 89.5 KB
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"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>The Swift Programming Language: Initialization</title>
<link rel="stylesheet" type="text/css" href="resource/style-1.1.15.css">
<meta charset="utf-8"> <script>window["_GOOG_TRANS_EXT_VER"] = "1";</script></head>
<body id="conceptual_flow_with_tasks" class="jazz">
<div id="_omniture_top">
</div>
<section id="valence">
<div class="content-wrapper">
<p id="hierarchial_navigation">
<span id="book_title">The Swift Programming Language</span>
</p>
<img id="shortstack" src="resource/shortstack_2x.png">
</div>
</section>
<div class="content-wrapper">
<nav class="book-parts hideInXcode" role="navigation">
<ul class="nav-parts">
<li data-id="TP40014097-CH1-XID_27" class="part-name">Welcome to Swift
<ul class="nav-chapters">
<li class="nav-chapter nav-visited-chapter">
<a href="About Swift.html#TP40014097-CH3-XID_0" data-id="TP40014097-CH3-XID_0" class="">About Swift</a>
</li>
<li class="nav-chapter">
<a href="A Swift Tour.html#TP40014097-CH2-XID_1" data-id="TP40014097-CH2-XID_1" class="">A Swift Tour</a>
</li>
</ul>
</li><li data-id="TP40014097-CH4-XID_299" class="part-name nav-part-active open-part">Language Guide
<ul class="nav-chapters" style="height: 607px;">
<li class="nav-chapter">
<a href="The Basics.html#TP40014097-CH5-XID_399" data-id="TP40014097-CH5-XID_399" class="">The Basics</a>
</li>
<li class="nav-chapter">
<a href="Basic Operators.html#TP40014097-CH6-XID_70" data-id="TP40014097-CH6-XID_70" class="">Basic Operators</a>
</li>
<li class="nav-chapter">
<a href="Strings and Characters.html#TP40014097-CH7-XID_368" data-id="TP40014097-CH7-XID_368" class="">Strings and Characters</a>
</li>
<li class="nav-chapter">
<a href="Collection Types.html#TP40014097-CH8-XID_133" data-id="TP40014097-CH8-XID_133" class="">Collection Types</a>
</li>
<li class="nav-chapter">
<a href="Control Flow.html#TP40014097-CH9-XID_153" data-id="TP40014097-CH9-XID_153" class="">Control Flow</a>
</li>
<li class="nav-chapter">
<a href="Functions.html#TP40014097-CH10-XID_204" data-id="TP40014097-CH10-XID_204" class="">Functions</a>
</li>
<li class="nav-chapter">
<a href="Closures.html#TP40014097-CH11-XID_117" data-id="TP40014097-CH11-XID_117" class="">Closures</a>
</li>
<li class="nav-chapter">
<a href="Enumerations.html#TP40014097-CH12-XID_185" data-id="TP40014097-CH12-XID_185" class="">Enumerations</a>
</li>
<li class="nav-chapter">
<a href="Classes and Structures.html#TP40014097-CH13-XID_94" data-id="TP40014097-CH13-XID_94" class="">Classes and Structures</a>
</li>
<li class="nav-chapter">
<a href="Properties.html#TP40014097-CH14-XID_323" data-id="TP40014097-CH14-XID_323" class="">Properties</a>
</li>
<li class="nav-chapter">
<a href="Methods.html#TP40014097-CH15-XID_300" data-id="TP40014097-CH15-XID_300" class="">Methods</a>
</li>
<li class="nav-chapter">
<a href="Subscripts.html#TP40014097-CH16-XID_393" data-id="TP40014097-CH16-XID_393" class="">Subscripts</a>
</li>
<li class="nav-chapter ">
<a href="Inheritance.html" data-id="TP40014097-CH17-XID_251" >Inheritance</a>
</li>
<li class="nav-chapter nav-current-chapter" >
<a href="Initialization.html#TP40014097-CH18-XID_266" data-id="TP40014097-CH18-XID_266" class="nav-chapter-active">Initialization</a>
</li>
<li class="nav-chapter">
<a href="Deinitialization.html#TP40014097-CH19-XID_182" data-id="TP40014097-CH19-XID_182">Deinitialization</a>
</li>
<li class="nav-chapter">
<a href="Automatic Reference Counting.html#TP40014097-CH20-XID_50" data-id="TP40014097-CH20-XID_50">Automatic Reference Counting</a>
</li>
<li class="nav-chapter">
<a href="Optional Chaining.html#TP40014097-CH21-XID_312" data-id="TP40014097-CH21-XID_312">Optional Chaining</a>
</li>
<li class="nav-chapter">
<a href="Type Casting.html#TP40014097-CH22-XID_443" data-id="TP40014097-CH22-XID_443">Type Casting</a>
</li>
<li class="nav-chapter">
<a href="Nested Types.html#TP40014097-CH23-XID_309" data-id="TP40014097-CH23-XID_309">Nested Types</a>
</li>
<li class="nav-chapter">
<a href="Extensions.html#TP40014097-CH24-XID_191" data-id="TP40014097-CH24-XID_191">Extensions</a>
</li>
<li class="nav-chapter">
<a href="Protocols.html#TP40014097-CH25-XID_345" data-id="TP40014097-CH25-XID_345">Protocols</a>
</li>
<li class="nav-chapter">
<a href="Generics.html#TP40014097-CH26-XID_234" data-id="TP40014097-CH26-XID_234">Generics</a>
</li>
<li class="nav-chapter">
<a href="Advanced Operators.html#TP40014097-CH27-XID_28" data-id="TP40014097-CH27-XID_28">Advanced Operators</a>
</li>
</ul>
</li><li data-id="TP40014097-CH28-XID_912" class="part-name">Language Reference
<ul class="nav-chapters">
<li class="nav-chapter">
<a href="About the Language Reference.html#TP40014097-CH29-XID_453" data-id="TP40014097-CH29-XID_453" class="">About the Language Reference</a>
</li>
<li class="nav-chapter">
<a href="Lexical Structure.html#TP40014097-CH30-XID_794" data-id="TP40014097-CH30-XID_794">Lexical Structure</a>
</li>
<li class="nav-chapter">
<a href="Types.html#TP40014097-CH31-XID_988" data-id="TP40014097-CH31-XID_988">Types</a>
</li>
<li class="nav-chapter">
<a href="Expressions.html#TP40014097-CH32-XID_655" data-id="TP40014097-CH32-XID_655">Expressions</a>
</li>
<li class="nav-chapter">
<a href="Statements.html#TP40014097-CH33-XID_913" data-id="TP40014097-CH33-XID_913">Statements</a>
</li>
<li class="nav-chapter">
<a href="Declarations.html#TP40014097-CH34-XID_475" data-id="TP40014097-CH34-XID_475">Declarations</a>
</li>
<li class="nav-chapter">
<a href="Attributes.html#TP40014097-CH35-XID_460" data-id="TP40014097-CH35-XID_460">Attributes</a>
</li>
<li class="nav-chapter">
<a href="Patterns.html#TP40014097-CH36-XID_878" data-id="TP40014097-CH36-XID_878">Patterns</a>
</li>
<li class="nav-chapter">
<a href="Generic Parameters and Arguments.html#TP40014097-CH37-XID_774" data-id="TP40014097-CH37-XID_774">Generic Parameters and Arguments</a>
</li>
<li class="nav-chapter">
<a href="Summary of the Grammar.html#TP40014097-CH38-XID_1030" data-id="TP40014097-CH38-XID_1030">Summary of the Grammar</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="chapter">
<a name="TP40014097-CH18"></a><a name="TP40014097-CH18-XID_266"></a>
<div class="pixel-line"></div>
<h2 class="chapter-name chapter-name-short">Initialization</h2>
<section id="mini_toc" class="hideInXcode" role="navigation">
<div id="mini_toc_button">
<p>On This Page</p>
</div>
<ul class="list-bullet">
<li class="item">
<p class="para">
<a href="#TP40014097-CH18-XID_267">
Setting Initial Values for Stored Properties
</a>
</p>
</li>
<li class="item">
<p class="para">
<a href="#TP40014097-CH18-XID_272">
Customizing Initialization
</a>
</p>
</li>
<li class="item">
<p class="para">
<a href="#TP40014097-CH18-XID_279">
Default Initializers
</a>
</p>
</li>
<li class="item">
<p class="para">
<a href="#TP40014097-CH18-XID_281">
Initializer Delegation for Value Types
</a>
</p>
</li>
<li class="item">
<p class="para">
<a href="#TP40014097-CH18-XID_284">
Class Inheritance and Initialization
</a>
</p>
</li>
<li class="item">
<p class="para">
<a href="#TP40014097-CH18-XID_297">
Setting a Default Property Value with a Closure or Function
</a>
</p>
</li>
</ul>
</section>
<section class="section">
<p class="para">
<em>Initialization</em> is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready to for use.
</p>
<p class="para">
You implement this initialization process by defining <em>initializers</em>, which are like special methods that can be called to create a new instance of a particular type. Unlike Objective-C initializers, Swift initializers do not return a value. Their primary role is to ensure that new instances of a type are correctly initialized before they are used for the first time.
</p>
<p class="para">
Instances of class types can also implement a <em>deinitializer</em>, which performs any custom cleanup just before an instance of that class is deallocated. For more information about deinitializers, see <span class="x-name"><a href="Deinitialization.html#TP40014097-CH19-XID_182" data-id="TP40014097-CH19-XID_182">Deinitialization</a></span>.
</p>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_267"></a>
<h3 class="section-name" tabindex="0">Setting Initial Values for Stored Properties</h3>
<p class="para">
Classes and structures <em>must</em> set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
</p><p class="para">
You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition. These actions are described in the following sections.
</p><div class="note">
<a name="TP40014097-CH18-XID_268"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">When you assign a default value to a stored property, or set its initial value within an initializer, the value of that property is set directly, without calling any property observers.
</p>
</aside>
</div>
<section class="section">
<a name="TP40014097-CH18-XID_269"></a>
<h3 class="section-name" tabindex="0">Initializers</h3>
<p class="para">
<em>Initializers</em> are called to create a new instance of a particular type. In its simplest form, an initializer is like an instance method with no parameters, written using the <code class="code-voice">init</code> keyword.
</p><p class="para">
The example below defines a new structure called <code class="code-voice">Fahrenheit</code> to store temperatures expressed in the Fahrenheit scale. The <code class="code-voice">Fahrenheit</code> structure has one stored property, <code class="code-voice">temperature</code>, which is of type <code class="code-voice">Double</code>:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Fahrenheit</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">temperature</span>: <span class="n"></span></code></li>
<li><code class="code-voice"> <span class="kt">init</span>() {</code></li>
<li><code class="code-voice"> <span class="vc">temperature</span> = <span class="m">32.0</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">var</span> <span class="vc">f</span> = <span class="vc">Fahrenheit</span>()</code></li>
<li><code class="code-voice"><span class="vc">println</span>(<span class="s">"The default temperature is </span>\(<span class="vc">f</span>.<span class="vc">temperature</span>)<span class="s">° Fahrenheit"</span>)</code></li>
<li><code class="code-voice"><span class="c">// prints "The default temperature is 32.0° Fahrenheit"</span></code></li>
</ul>
</div>
</section><p class="para">
The structure defines a single initializer, <code class="code-voice">init</code>, with no parameters, which initializes the stored temperature with a value of <code class="code-voice">32.0</code> (the freezing point of water when expressed in the Fahrenheit scale).
</p>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_270"></a>
<h3 class="section-name" tabindex="0">Default Property Values</h3>
<p class="para">
You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a <em>default property value</em> as part of the property’s declaration. You specify a default property value by assigning an initial value to the property when it is defined.
</p><div class="note">
<a name="TP40014097-CH18-XID_271"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">If a property always takes the same initial value, provide a default value rather than setting a value within an initializer. The end result is the same, but the default value ties the property’s initialization more closely to its declaration. It makes for shorter, clearer initializers and enables you to infer the type of the property from its default value. The default value also makes it easier for you to take advantage of default initializers and initializer inheritance, as described later in this chapter.
</p>
</aside>
</div><p class="para">
You can write the <code class="code-voice">Fahrenheit</code> structure from above in a simpler form by providing a default value for its <code class="code-voice">temperature</code> property at the point that the property is declared:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Fahrenheit</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">temperature</span> = <span class="m">32.0</span></code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section>
</section>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_272"></a>
<h3 class="section-name" tabindex="0">Customizing Initialization</h3>
<p class="para">
You can customize the initialization process with input parameters and optional property types, or by modifying constant properties during initialization, as described in the following sections.
</p>
<section class="section">
<a name="TP40014097-CH18-XID_273"></a>
<h3 class="section-name" tabindex="0">Initialization Parameters</h3>
<p class="para">
You can provide <em>initialization parameters</em> as part of an initializer’s definition, to define the types and names of values that customize the initialization process. Initialization parameters have the same capabilities and syntax as function and method parameters.
</p><p class="para">
The following example defines a structure called <code class="code-voice">Celsius</code>, which stores temperatures expressed in the Celsius scale. The <code class="code-voice">Celsius</code> structure implements two custom initializers called <code class="code-voice">init(fromFahrenheit:)</code> and <code class="code-voice">init(fromKelvin:)</code>, which initialize a new instance of the structure with a value from a different temperature scale:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Celsius</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">temperatureInCelsius</span>: <span class="n"></span> = <span class="m">0.0</span></code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">fromFahrenheit</span> <span class="vc">fahrenheit</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">temperatureInCelsius</span> = (<span class="vc">fahrenheit</span> - <span class="m">32.0</span>) / <span class="m">1.8</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">fromKelvin</span> <span class="vc">kelvin</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">temperatureInCelsius</span> = <span class="vc">kelvin</span> - <span class="m">273.15</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">boilingPointOfWater</span> = <span class="vc">Celsius</span>(<span class="vc">fromFahrenheit</span>: <span class="m">212.0</span>)</code></li>
<li><code class="code-voice"><span class="c">// boilingPointOfWater.temperatureInCelsius is 100.0</span></code></li>
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">freezingPointOfWater</span> = <span class="vc">Celsius</span>(<span class="vc">fromKelvin</span>: <span class="m">273.15</span>)</code></li>
<li><code class="code-voice"><span class="c">// freezingPointOfWater.temperatureInCelsius is 0.0</span></code></li>
</ul>
</div>
</section><p class="para">
The first initializer has a single initialization parameter with an external name of <code class="code-voice">fromFahrenheit</code> and a local name of <code class="code-voice">fahrenheit</code>. The second initializer has a single initialization parameter with an external name of <code class="code-voice">fromKelvin</code> and a local name of <code class="code-voice">kelvin</code>. Both initializers convert their single argument into a value in the Celsius scale and store this value in a property called <code class="code-voice">temperatureInCelsius</code>.
</p>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_274"></a>
<h3 class="section-name" tabindex="0">Local and External Parameter Names</h3>
<p class="para">
As with function and method parameters, initialization parameters can have both a local name for use within the initializer’s body and an external name for use when calling the initializer.
</p><p class="para">
However, initializers do not have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer’s parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic external name for <em>every</em> parameter in an initializer if you don’t provide an external name yourself. This automatic external name is the same as the local name, as if you had written a hash symbol before every initialization parameter.
</p><div class="note">
<a name="TP40014097-CH18-XID_275"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">If you do not want to provide an external name for a parameter in an initializer, provide an underscore (<code class="code-voice">_</code>) as an explicit external name for that parameter to override the default behavior described above.
</p>
</aside>
</div><p class="para">
The following example defines a structure called <code class="code-voice">Color</code>, with three constant properties called <code class="code-voice">red</code>, <code class="code-voice">green</code>, and <code class="code-voice">blue</code>. These properties store a value between <code class="code-voice">0.0</code> and <code class="code-voice">1.0</code> to indicate the amount of red, green, and blue in the color.
</p><p class="para">
<code class="code-voice">Color</code> provides an initializer with three appropriately named parameters of type <code class="code-voice">Double</code>:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Color</span> {</code></li>
<li><code class="code-voice"> <span class="kt">let</span> <span class="vc">red</span> = <span class="m">0.0</span>, <span class="vc">green</span> = <span class="m">0.0</span>, <span class="vc">blue</span> = <span class="m">0.0</span></code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">red</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">red</span> = <span class="vc">red</span></code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">green</span> = <span class="vc">green</span></code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">blue</span> = <span class="vc">blue</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
Whenever you create a new <code class="code-voice">Color</code> instance, you call its initializer using external names for each of the three color components:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">magenta</span> = <span class="vc">Color</span>(<span class="vc">red</span>: <span class="m">1.0</span>, <span class="vc">green</span>: <span class="m">0.0</span>, <span class="vc">blue</span>: <span class="m">1.0</span>)</code></li>
</ul>
</div>
</section><p class="para">
Note that it is not possible to call this initializer without using the external names. External names must always be used in an intializer if they are defined, and omitting them is a compile-time error:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">veryGreen</span> = <span class="vc">Color</span>(<span class="m">0.0</span>, <span class="m">1.0</span>, <span class="m">0.0</span>)</code></li>
<li><code class="code-voice"><span class="c">// this reports a compile-time error - external names are required</span></code></li>
</ul>
</div>
</section>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_276"></a>
<h3 class="section-name" tabindex="0">Optional Property Types</h3>
<p class="para">
If your custom type has a stored property that is logically allowed to have “no value”—perhaps because its value cannot be set during initialization, or because it is allowed to have “no value” at some later point—declare the property with an <em>optional</em> type. Properties of optional type are automatically initialized with a value of <code class="code-voice">nil</code>, indicating that the property is deliberately intended to have “no value yet” during initialization.
</p><p class="para">
The following example defines a class called <code class="code-voice">SurveyQuestion</code>, with an optional <code class="code-voice">String</code> property called <code class="code-voice">response</code>:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">class</span> <span class="vc">SurveyQuestion</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">text</span>: <span class="n"></span></code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">response</span>: <span class="n"></span>?</code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">text</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">text</span> = <span class="vc">text</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">ask</span>() {</code></li>
<li><code class="code-voice"> <span class="vc">println</span>(<span class="vc">text</span>)</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">cheeseQuestion</span> = <span class="vc">SurveyQuestion</span>(<span class="vc">text</span>: <span class="s">"Do you like cheese?"</span>)</code></li>
<li><code class="code-voice"><span class="vc">cheeseQuestion</span>.<span class="vc">ask</span>()</code></li>
<li><code class="code-voice"><span class="c">// prints "Do you like cheese?"</span></code></li>
<li><code class="code-voice"><span class="vc">cheeseQuestion</span>.<span class="vc">response</span> = <span class="s">"Yes, I do like cheese."</span></code></li>
</ul>
</div>
</section><p class="para">
The response to a survey question cannot be known until it is asked, and so the <code class="code-voice">response</code> property is declared with a type of <code class="code-voice">String?</code>, or “optional <code class="code-voice">String</code>”. It is automatically assigned a default value of <code class="code-voice">nil</code>, meaning “no string yet”, when a new instance of <code class="code-voice">SurveyQuestion</code> is initialized.
</p>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_277"></a>
<h3 class="section-name" tabindex="0">Modifying Constant Properties During Initialization</h3>
<p class="para">
You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.
</p><div class="note">
<a name="TP40014097-CH18-XID_278"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">For class instances, a constant property can only be modified during initialization by the class that introduces it. It cannot be modified by a subclass.
</p>
</aside>
</div><p class="para">
You can revise the <code class="code-voice">SurveyQuestion</code> example from above to use a constant property rather than a variable property for the <code class="code-voice">text</code> property of the question, to indicate that the question does not change once an instance of <code class="code-voice">SurveyQuestion</code> is created. Even though the <code class="code-voice">text</code> property is now a constant, it can still be set within the class’s initializer:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">class</span> <span class="vc">SurveyQuestion</span> {</code></li>
<li><code class="code-voice"> <span class="kt">let</span> <span class="vc">text</span>: <span class="n"></span></code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">response</span>: <span class="n"></span>?</code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">text</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">text</span> = <span class="vc">text</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">ask</span>() {</code></li>
<li><code class="code-voice"> <span class="vc">println</span>(<span class="vc">text</span>)</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">beetsQuestion</span> = <span class="vc">SurveyQuestion</span>(<span class="vc">text</span>: <span class="s">"How about beets?"</span>)</code></li>
<li><code class="code-voice"><span class="vc">beetsQuestion</span>.<span class="vc">ask</span>()</code></li>
<li><code class="code-voice"><span class="c">// prints "How about beets?"</span></code></li>
<li><code class="code-voice"><span class="vc">beetsQuestion</span>.<span class="vc">response</span> = <span class="s">"I also like beets. (But not with cheese.)"</span></code></li>
</ul>
</div>
</section>
</section>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_279"></a>
<h3 class="section-name" tabindex="0">Default Initializers</h3>
<p class="para">
Swift provides a <em>default initializer</em> for any structure or base class that provides default values for all of its properties and does not provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.
</p><p class="para">
This example defines a class called <code class="code-voice">ShoppingListItem</code>, which encapsulates the name, quantity, and purchase state of an item in a shopping list:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">class</span> <span class="vc">ShoppingListItem</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">name</span>: <span class="n"></span>?</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">quantity</span> = <span class="m">1</span></code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">purchased</span> = <span class="vc">false</span></code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">var</span> <span class="vc">item</span> = <span class="vc">ShoppingListItem</span>()</code></li>
</ul>
</div>
</section><p class="para">
Because all properties of the <code class="code-voice">ShoppingListItem</code> class have default values, and because it is a base class with no superclass, <code class="code-voice">ShoppingListItem</code> automatically gains a default initializer implementation that creates a new instance with all of its properties set to their default values. (The <code class="code-voice">name</code> property is an optional <code class="code-voice">String</code> property, and so it automatically receives a default value of <code class="code-voice">nil</code>, even though this value is not written in the code.) The example above uses the default initializer for the <code class="code-voice">ShoppingListItem</code> class to create a new instance of the class with initializer syntax, written as <code class="code-voice">ShoppingListItem()</code>, and assigns this new instance to a variable called <code class="code-voice">item</code>.
</p>
<section class="section">
<a name="TP40014097-CH18-XID_280"></a>
<h3 class="section-name" tabindex="0">Memberwise Initializers for Structure Types</h3>
<p class="para">
In addition to the default initializers mentioned above, structure types automatically receive a <em>memberwise initializer</em> if they provide default values for all of their stored properties and do not define any of their own custom initializers.
</p><p class="para">
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name.
</p><p class="para">
The example below defines a structure called <code class="code-voice">Size</code> with two properties called <code class="code-voice">width</code> and <code class="code-voice">height</code>. Both properties are inferred to be of type <code class="code-voice">Double</code> by assigning a default value of <code class="code-voice">0.0</code>.
</p><p class="para">
Because both stored properties have a default value, the <code class="code-voice">Size</code> structure automatically receives an <code class="code-voice">init(width:height:)</code> memberwise initializer, which you can use to initialize a new <code class="code-voice">Size</code> instance:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Size</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">width</span> = <span class="m">0.0</span>, <span class="vc">height</span> = <span class="m">0.0</span></code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">twoByTwo</span> = <span class="vc">Size</span>(<span class="vc">width</span>: <span class="m">2.0</span>, <span class="vc">height</span>: <span class="m">2.0</span>)</code></li>
</ul>
</div>
</section>
</section>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_281"></a>
<h3 class="section-name" tabindex="0">Initializer Delegation for Value Types</h3>
<p class="para">
Initializers can call other initializers to perform part of an instance’s initialization. This process, known as <em>initializer delegation</em>, avoids duplicating code across multiple initializers.
</p><p class="para">
The rules for how initializer delegation works, and for what forms of delegation are allowed, are different for value types and class types. Value types (structures and enumerations) do not support inheritance, and so their initializer delegation process is relatively simple, because they can only delegate to another initializer that they provide themselves. Classes, however, can inherit from other classes, as described in <span class="x-name"><a href="#TP40014097-CH17-XID_251" data-id="TP40014097-CH17-XID_251">Inheritance</a></span>. This means that classes have additional responsibilities for ensuring that all stored properties they inherit are assigned a suitable value during initialization. These responsibilities are described in <span class="x-name"><a href="#TP40014097-CH18-XID_284" data-id="TP40014097-CH18-XID_284">Class Inheritance and Initialization</a></span> below.
</p><p class="para">
For value types, you use <code class="code-voice">self.init</code> to refer to other initializers from the same value type when writing your own custom initializers. You can only call <code class="code-voice">self.init</code> from within an initializer.
</p><p class="para">
Note that if you define a custom initializer for a value type, you will no longer have access to the default initializer (or the memberwise structure initializer, if it is a structure) for that type. This constraint prevents a situation in which you provide a more complex initializer that performs additional essential setup is circumvented by someone accidentally using one of the automatic initializers instead.
</p><div class="note">
<a name="TP40014097-CH18-XID_282"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type’s original implementation. For more information, see <span class="x-name"><a href="Extensions.html#TP40014097-CH24-XID_191" data-id="TP40014097-CH24-XID_191">Extensions</a></span>.
</p>
</aside>
</div><p class="para">
The following example defines a custom <code class="code-voice">Rect</code> structure to represent a geometric rectangle. The example requires two supporting structures called <code class="code-voice">Size</code> and <code class="code-voice">Point</code>, both of which provide default values of <code class="code-voice">0.0</code> for all of their properties:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Size</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">width</span> = <span class="m">0.0</span>, <span class="vc">height</span> = <span class="m">0.0</span></code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Point</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">x</span> = <span class="m">0.0</span>, <span class="vc">y</span> = <span class="m">0.0</span></code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
You can initialize the <code class="code-voice">Rect</code> structure below in one of three ways—by using its default zero-initialized <code class="code-voice">origin</code> and <code class="code-voice">size</code> property values, by providing a specific origin point and size, or by providing a specific center point and size. These initialization options are represented by three custom initializers that are part of the <code class="code-voice">Rect</code> structure’s definition:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">struct</span> <span class="vc">Rect</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">origin</span> = <span class="vc">Point</span>()</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">size</span> = <span class="vc">Size</span>()</code></li>
<li><code class="code-voice"> <span class="kt">init</span>() {}</code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">origin</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">origin</span> = <span class="vc">origin</span></code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">size</span> = <span class="vc">size</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">center</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">let</span> <span class="vc">originX</span> = <span class="vc">center</span>.<span class="vc">x</span> - (<span class="vc">size</span>.<span class="vc">width</span> / <span class="m">2</span>)</code></li>
<li><code class="code-voice"> <span class="kt">let</span> <span class="vc">originY</span> = <span class="vc">center</span>.<span class="vc">y</span> - (<span class="vc">size</span>.<span class="vc">height</span> / <span class="m">2</span>)</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="kt">init</span>(<span class="vc">origin</span>: <span class="vc">Point</span>(<span class="vc">x</span>: <span class="vc">originX</span>, <span class="vc">y</span>: <span class="vc">originY</span>), <span class="vc">size</span>: <span class="vc">size</span>)</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
The first <code class="code-voice">Rect</code> initializer, <code class="code-voice">init()</code>, is functionally the same as the default initializer that the structure would have received if it did not have its own custom initializers. This initializer has an empty body, represented by an empty pair of curly braces <code class="code-voice">{}</code>, and does not perfom any initialization. Calling this initializer returns a <code class="code-voice">Rect</code> instance whose <code class="code-voice">origin</code> and <code class="code-voice">size</code> properties are both initialized with the default values of <code class="code-voice">Point(x: 0.0, y: 0.0)</code> and <code class="code-voice">Size(width: 0.0, height: 0.0)</code> from their property definitions:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">basicRect</span> = <span class="vc">Rect</span>()</code></li>
<li><code class="code-voice"><span class="c">// basicRect's origin is (0.0, 0.0) and its size is (0.0, 0.0)</span></code></li>
</ul>
</div>
</section><p class="para">
The second <code class="code-voice">Rect</code> initializer, <code class="code-voice">init(origin:size:)</code>, is functionally the same as the memberwise initializer that the structure would have received if it did not have its own custom initializers. This initializer simply assigns the <code class="code-voice">origin</code> and <code class="code-voice">size</code> argument values to the appropriate stored properties:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">originRect</span> = <span class="vc">Rect</span>(<span class="vc">origin</span>: <span class="vc">Point</span>(<span class="vc">x</span>: <span class="m">2.0</span>, <span class="vc">y</span>: <span class="m">2.0</span>),</code></li>
<li><code class="code-voice"> <span class="vc">size</span>: <span class="vc">Size</span>(<span class="vc">width</span>: <span class="m">5.0</span>, <span class="vc">height</span>: <span class="m">5.0</span>))</code></li>
<li><code class="code-voice"><span class="c">// originRect's origin is (2.0, 2.0) and its size is (5.0, 5.0)</span></code></li>
</ul>
</div>
</section><p class="para">
The third <code class="code-voice">Rect</code> initializer, <code class="code-voice">init(center:size:)</code>, is slightly more complex. It starts by calculating an appropriate origin point based on a <code class="code-voice">center</code> point and a <code class="code-voice">size</code> value. It then calls (or <em>delegates</em>) to the <code class="code-voice">init(origin:size:)</code> initializer, which stores the new origin and size values in the appropriate properties:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">centerRect</span> = <span class="vc">Rect</span>(<span class="vc">center</span>: <span class="vc">Point</span>(<span class="vc">x</span>: <span class="m">4.0</span>, <span class="vc">y</span>: <span class="m">4.0</span>),</code></li>
<li><code class="code-voice"> <span class="vc">size</span>: <span class="vc">Size</span>(<span class="vc">width</span>: <span class="m">3.0</span>, <span class="vc">height</span>: <span class="m">3.0</span>))</code></li>
<li><code class="code-voice"><span class="c">// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)</span></code></li>
</ul>
</div>
</section><p class="para">
The <code class="code-voice">init(center:size:)</code> initializer could have assigned the new values of <code class="code-voice">origin</code> and <code class="code-voice">size</code> to the appropriate properties itself. However, it is more convenient (and clearer in intent) for the <code class="code-voice">init(center:size:)</code> initializer to take advantage of an existing initializer that already provides exactly that functionality.
</p><div class="note">
<a name="TP40014097-CH18-XID_283"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">For an alternative way to write this example without defining the <code class="code-voice">init()</code> and <code class="code-voice">init(origin:size:)</code> initializers yourself, see <span class="x-name"><a href="Extensions.html#TP40014097-CH24-XID_191" data-id="TP40014097-CH24-XID_191">Extensions</a></span>.
</p>
</aside>
</div>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_284"></a>
<h3 class="section-name" tabindex="0">Class Inheritance and Initialization</h3>
<p class="para">
All of a class’s stored properties—including any properties the class inherits from its superclass—<em>must</em> be assigned an initial value during initialization.
</p><p class="para">
Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.
</p>
<section class="section">
<a name="TP40014097-CH18-XID_285"></a>
<h3 class="section-name" tabindex="0">Designated Initializers and Convenience Initializers</h3>
<p class="para">
<em>Designated initializers</em> are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.
</p><p class="para">
Classes tend to have very few designated initializers, and it is quite common for a class to have only one. Designated initializers are “funnel” points through which initialization takes place, and through which the initialization process continues up the superclass chain.
</p><p class="para">
Every class must have at least one designated initializer. In some cases, this requirement is satisfied by inheriting one or more designated initializers from a superclass, as described in <span class="x-name"><a href="Initialization.html#TP40014097-CH18-XID_292" data-id="TP40014097-CH18-XID_292">Automatic Initializer Inheritance</a></span> below.
</p><p class="para">
<em>Convenience initializers</em> are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.
</p><p class="para">
You do not have to provide convenience initializers if your class does not require them. Create convenience initializers whenever a shortcut to a common initialization pattern will save time or make initialization of the class clearer in intent.
</p>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_286"></a>
<h3 class="section-name" tabindex="0">Initializer Chaining</h3>
<p class="para">
To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:
</p><dl class="term-definition termdef">
<dt class="term"><strong>Rule 1</strong></dt><dd class="definition"><p class="para">
Designated initializers must call a designated initializer from their immediate superclass.
</p></dd><dt class="term"><strong>Rule 2</strong></dt><dd class="definition"><p class="para">
Convenience initializers must call another initializer available in the <em>same</em> class.
</p></dd><dt class="term"><strong>Rule 3</strong></dt><dd class="definition"><p class="para">
Convenience initializers must ultimately end up calling a designated initializer.
</p></dd>
</dl><p class="para">
A simple way to remember this is:
</p><ul class="list-bullet">
<li class="item"><p class="para">
Designated initializers must always delegate <em>up</em>.
</p>
</li><li class="item"><p class="para">
Convenience initializers must always delegate <em>across</em>.
</p>
</li>
</ul><p class="para">
These rules are illustrated in the figure below:
</p><figure class="figure">
<span class="caption"></span>
<img src="resource/initializerDelegation01_2x.png" alt="image: ../Art/initializerDelegation01_2x.png" width="448" height="214">
</figure><p class="para">
Here, the superclass has a single designated initializer and two convenience initializers. One convenience initializer calls another convenience initializer, which in turn calls the single designated initializer. This satisfies rules 2 and 3 from above. The superclass does not itself have a further superclass, and so rule 1 does not apply.
</p><p class="para">
The subclass in this figure has two designated initializers and one convenience initializer. The convenience initializer must call one of the two designated initializers, because it can only call another initializer from the same class. This satisfies rules 2 and 3 from above. Both designated initializers must call the single designated initializer from the superclass, to satisfy rule 1 from above.
</p><div class="note">
<a name="TP40014097-CH18-XID_287"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">These rules don’t affect how users of your classes <em>create</em> instances of each class. Any initializer in the diagram above can be used to create a fully-initialized instance of the class they belong to. The rules only affect how you write the class’s implementation.
</p>
</aside>
</div><p class="para">
The figure below shows a more complex class hierarchy for four classes. It illustrates how the designated initializers in this hierarchy act as “funnel” points for class initialization, simplifying the interrelationships among classes in the chain:
</p><figure class="figure">
<span class="caption"></span>
<img src="resource/initializerDelegation02_2x.png" alt="image: ../Art/initializerDelegation02_2x.png" width="448" height="444">
</figure>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_288"></a>
<h3 class="section-name" tabindex="0">Two-Phase Initialization</h3>
<p class="para">
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
</p><p class="para">
The use of a two-phase initialization process makes initialization safe, while still giving complete flexibility to each class in a class hierarchy. Two-phase initialization prevents property values from being accessed before they are initialized, and prevents property values from being set to a different value by another initializer unexpectedly.
</p><div class="note">
<a name="TP40014097-CH18-XID_289"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">Swift’s two-phase initialization process is similar to initialization in Objective-C. The main difference is that during phase 1, Objective-C assigns zero or null values (such as <code class="code-voice">0</code> or <code class="code-voice">nil</code>) to every property. Swift’s initialization flow is more flexible in that it lets you set custom initial values, and can cope with types for which <code class="code-voice">0</code> or <code class="code-voice">nil</code> is not a valid default value.
</p>
</aside>
</div><p class="para">
Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:
</p><dl class="term-definition termdef">
<dt class="term"><strong>Safety check 1</strong></dt><dd class="definition"><p class="para">
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
</p></dd>
</dl><p class="para">
As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.
</p><dl class="term-definition termdef">
<dt class="term"><strong>Safety check 2</strong></dt><dd class="definition"><p class="para">
A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn’t, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization.
</p></dd><dt class="term"><strong>Safety check 3</strong></dt><dd class="definition"><p class="para">
A convenience initializer must delegate to another initializer before assigning a value to <em>any</em> property (including properties defined by the same class). If it doesn’t, the new value the convenience initializer assigns will be overwritten by its own class’s designated initializer.
</p></dd><dt class="term"><strong>Safety check 4</strong></dt><dd class="definition"><p class="para">
An initializer cannot call any instance methods, read the values of any instance properties, or refer to <code class="code-voice">self</code> as a value until after the first phase of initialization is complete.
</p></dd>
</dl><p class="para">
The class instance is not fully valid until the first phase ends. Properties can only be accessed, and methods can only be called, once the class instance is known to be valid at the end of the first phase.
</p><p class="para">
Here’s how two-phase initialization plays out, based on the four safety checks above:
</p><p class="para">
<strong>Phase 1</strong>
</p><ul class="list-bullet">
<li class="item"><p class="para">
A designated or convenience initializer is called on a class.
</p>
</li><li class="item"><p class="para">
Memory for a new instance of that class is allocated. The memory is not yet initialized.
</p>
</li><li class="item"><p class="para">
A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
</p>
</li><li class="item"><p class="para">
The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
</p>
</li><li class="item"><p class="para">
This continues up the class inheritance chain until the top of the chain is reached.
</p>
</li><li class="item"><p class="para">
Once the top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value, the instance’s memory is considered to be fully initialized, and phase 1 is complete.
</p>
</li>
</ul><p class="para">
<strong>Phase 2</strong>
</p><ul class="list-bullet">
<li class="item"><p class="para">
Working back down from the top of the chain, each designated initializer in the chain has the option to customize the instance further. Initializers are now able to access <code class="code-voice">self</code> and can modify its properties, call its instance methods, and so on.
</p>
</li><li class="item"><p class="para">
Finally, any convenience initializers in the chain have the option to customize the instance and to work with <code class="code-voice">self</code>.
</p>
</li>
</ul><p class="para">
Here’s how phase 1 looks for an initialization call for a hypothetical subclass and superclass:
</p><figure class="figure">
<span class="caption"></span>
<img src="resource/twoPhaseInitialization01_2x.png" alt="image: ../Art/twoPhaseInitialization01_2x.png" width="448" height="214">
</figure><p class="para">
In this example, initialization begins with a call to a convenience initializer on the subclass. This convenience initializer cannot yet modify any properties. It delegates across to a designated initializer from the same class.
</p><p class="para">
The designated initializer makes sure that all of the subclass’s properties have a value, as per safety check 1. It then calls a designated initializer on its superclass to continue the initialization up the chain.
</p><p class="para">
The superclass’s designated initializer makes sure that all of the superclass properties have a value. There are no further superclasses to initialize, and so no further delegation is needed.
</p><p class="para">
As soon as all properties of the superclass have an initial value, its memory is considered fully initialized, and Phase 1 is complete.
</p><p class="para">
Here’s how phase 2 looks for the same initialization call:
</p><figure class="figure">
<span class="caption"></span>
<img src="resource/twoPhaseInitialization02_2x.png" alt="image: ../Art/twoPhaseInitialization02_2x.png" width="448" height="214">
</figure><p class="para">
The superclass’s designated initializer now has an opportunity to customize the instance further (although it does not have to).
</p><p class="para">
Once the superclass’s designated initializer is finished, the subclass’s designated initializer can perform additional customization (although again, it does not have to).
</p><p class="para">
Finally, once the subclass’s designated initializer is finished, the convenience initializer that was originally called can perform additional customization.
</p>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_290"></a>
<h3 class="section-name" tabindex="0">Initializer Inheritance and Overriding</h3>
<p class="para">
Unlike subclasses in Objective-C, Swift subclasses do not not inherit their superclass initializers by default. Swift’s approach prevents a situation in which a simple initializer from a superclass is automatically inherited by a more specialized subclass and is used to create a new instance of the subclass that is not fully or correctly initialized.
</p><p class="para">
If you want your custom subclass to present one or more of the same initializers as its superclass—perhaps to perform some customization during initialization—you can provide an overriding implementation of the same initializer within your custom subclass.
</p><p class="para">
If the initializer you are overriding is a <em>designated</em> initializer, you can override its implementation in your subclass and call the superclass version of the initializer from within your overriding version.
</p><p class="para">
If the initializer you are overriding is a <em>convenience</em> initializer, your override must call another designated initializer from its own subclass, as per the rules described above in <span class="x-name"><a href="Initialization.html#TP40014097-CH18-XID_286" data-id="TP40014097-CH18-XID_286">Initializer Chaining</a></span>.
</p><div class="note">
<a name="TP40014097-CH18-XID_291"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">Unlike methods, properties, and subscripts, you do not need to write the <code class="code-voice">override</code> keyword when overriding an initializer.
</p>
</aside>
</div>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_292"></a>
<h3 class="section-name" tabindex="0">Automatic Initializer Inheritance</h3>
<p class="para">
As mentioned above, subclasses do not not inherit their superclass initializers by default. However, superclass initializers <em>are</em> automatically inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it is safe to do so.
</p><p class="para">
Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:
</p><dl class="term-definition termdef">
<dt class="term"><strong>Rule 1</strong></dt><dd class="definition"><p class="para">
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
</p></dd><dt class="term"><strong>Rule 2</strong></dt><dd class="definition"><p class="para">
If your subclass provides an implementation of <em>all</em> of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.
</p></dd>
</dl><p class="para">
These rules apply even if your subclass adds further convenience initializers.
</p><div class="note">
<a name="TP40014097-CH18-XID_293"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">A subclass can implement a superclass designated initializer as a subclass convenience initializer as part of satisfying rule 2.
</p>
</aside>
</div>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_294"></a>
<h3 class="section-name" tabindex="0">Syntax for Designated and Convenience Initializers</h3>
<p class="para">
Designated initializers for classes are written in the same way as simple initializers for value types:
</p><span class="caption"></span>
<div class="code-outline">
<ul class="code-outline-lines">
<li><pre class="code-voice"><span class="kt">init</span>(<em class="variable-text">parameters</em>) {</pre></li><li><pre class="code-voice"> <em class="variable-text">statements</em></pre></li><li><pre class="code-voice">}</pre></li>
</ul>
</div><p class="para">
Convenience initializers are written in the same style, but with the <code class="code-voice">convenience</code> keyword placed before the <code class="code-voice">init</code> keyword, separated by a space:
</p><span class="caption"></span>
<div class="code-outline">
<ul class="code-outline-lines">
<li><pre class="code-voice"><span class="kt">convenience</span> <span class="kt">init</span>(<em class="variable-text">parameters</em>) {</pre></li><li><pre class="code-voice"> <em class="variable-text">statements</em></pre></li><li><pre class="code-voice">}</pre></li>
</ul>
</div>
</section>
<section class="section">
<a name="TP40014097-CH18-XID_295"></a>
<h3 class="section-name" tabindex="0">Designated and Convenience Initializers in Action</h3>
<p class="para">
The following example shows designated initializers, convenience initializers, and automatic initializer inheritance in action. This example defines a hierarchy of three classes called <code class="code-voice">Food</code>, <code class="code-voice">RecipeIngredient</code>, and <code class="code-voice">ShoppingListItem</code>, and demonstrates how their initializers interact.
</p><p class="para">
The base class in the hierarchy is called <code class="code-voice">Food</code>, which is a simple class to encapsulate the name of a foodstuff. The <code class="code-voice">Food</code> class introduces a single <code class="code-voice">String</code> property called <code class="code-voice">name</code> and provides two initializers for creating <code class="code-voice">Food</code> instances:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">class</span> <span class="vc">Food</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">name</span>: <span class="n"></span></code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">name</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">name</span> = <span class="vc">name</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">convenience</span> <span class="kt">init</span>() {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="kt">init</span>(<span class="vc">name</span>: <span class="s">"[Unnamed]"</span>)</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
The figure below shows the initializer chain for the <code class="code-voice">Food</code> class:
</p><figure class="figure">
<span class="caption"></span>
<img src="resource/initializersExample01_2x.png" alt="image: ../Art/initializersExample01_2x.png" width="482" height="136">
</figure><p class="para">
Classes do not have a default memberwise initializer, and so the <code class="code-voice">Food</code> class provides a designated initializer that takes a single argument called <code class="code-voice">name</code>. This initializer can be used to create a new <code class="code-voice">Food</code> instance with a specific name:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">namedMeat</span> = <span class="vc">Food</span>(<span class="vc">name</span>: <span class="s">"Bacon"</span>)</code></li>
<li><code class="code-voice"><span class="c">// namedMeat's name is "Bacon"</span></code></li>
</ul>
</div>
</section><p class="para">
The <code class="code-voice">init(name: String)</code> initializer from the <code class="code-voice">Food</code> class is provided as a <em>designated</em> initializer, because it ensures that all stored properties of a new <code class="code-voice">Food</code> instance are fully initialized. The <code class="code-voice">Food</code> class does not have a superclass, and so the <code class="code-voice">init(name: String)</code> initializer does not need to call <code class="code-voice">super.init()</code> to complete its initialization.
</p><p class="para">
The <code class="code-voice">Food</code> class also provides a <em>convenience</em> initializer, <code class="code-voice">init()</code>, with no arguments. The <code class="code-voice">init()</code> initializer provides a default placeholder name for a new food by delegating across to the <code class="code-voice">Food</code> class’s <code class="code-voice">init(name: String)</code> with a <code class="code-voice">name</code> value of <code class="code-voice">[Unnamed]</code>:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">let</span> <span class="vc">mysteryMeat</span> = <span class="vc">Food</span>()</code></li>
<li><code class="code-voice"><span class="c">// mysteryMeat's name is "[Unnamed]"</span></code></li>
</ul>
</div>
</section><p class="para">
The second class in the hierarchy is a subclass of <code class="code-voice">Food</code> called <code class="code-voice">RecipeIngredient</code>. The <code class="code-voice">RecipeIngredient</code> class models an ingredient in a cooking recipe. It introduces an <code class="code-voice">Int</code> property called <code class="code-voice">quantity</code> (in addition to the <code class="code-voice">name</code> property it inherits from <code class="code-voice">Food</code>) and defines two initializers for creating <code class="code-voice">RecipeIngredient</code> instances:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="kt">class</span> <span class="vc">RecipeIngredient</span>: <span class="n"></span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">quantity</span>: <span class="n"></span></code></li>
<li><code class="code-voice"> <span class="kt">init</span>(<span class="vc">name</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">quantity</span> = <span class="vc">quantity</span></code></li>
<li><code class="code-voice"> <span class="kt">super</span>.<span class="kt">init</span>(<span class="vc">name</span>: <span class="vc">name</span>)</code></li>