-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethods.html
More file actions
664 lines (553 loc) · 47 KB
/
Methods.html
File metadata and controls
664 lines (553 loc) · 47 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
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>The Swift Programming Language: Methods</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>
<a name="TP40014097" title="The Swift Programming Language"></a>
<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 nav-current-chapter">
<a href="Methods.html" data-id="TP40014097-CH15-XID_300" class="nav-chapter-active">Methods</a>
</li>
<li class="nav-chapter">
<a href="Subscripts.html#TP40014097-CH16-XID_393" data-id="TP40014097-CH16-XID_393">Subscripts</a>
</li>
<li class="nav-chapter">
<a href="Inheritance.html#TP40014097-CH17-XID_251" data-id="TP40014097-CH17-XID_251">Inheritance</a>
</li>
<li class="nav-chapter">
<a href="Initialization.html#TP40014097-CH18-XID_266" data-id="TP40014097-CH18-XID_266">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-CH15"></a><a name="TP40014097-CH15-XID_300"></a>
<div class="pixel-line"></div>
<h2 class="chapter-name chapter-name-short">Methods</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-CH15-XID_301">
Instance Methods
</a>
</p>
</li>
<li class="item">
<p class="para">
<a href="#TP40014097-CH15-XID_307">
Type Methods
</a>
</p>
</li>
</ul>
</section>
<section class="section">
<p class="para">
<em>Methods</em> are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type. Classes, structures, and enumerations can also define type methods, which are associated with the type itself. Type methods are similar to class methods in Objective-C.
</p>
<p class="para">
The fact that structures and enumerations can define methods in Swift is a major difference from C and Objective-C. In Objective-C, classes are the only types that can define methods. In Swift, you can choose whether to define a class, structure, or enumeration, and still have the flexibility to define methods on the type you create.
</p>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_301"></a>
<h3 class="section-name" tabindex="0">Instance Methods</h3>
<p class="para">
<em>Instance methods</em> are functions that belong to instances of a particular class, structure, or enumeration. They support the functionality of those instances, either by providing ways to access and modify instance properties, or by providing functionality related to the instance’s purpose. Instance methods have exactly the same syntax as functions, as described in <span class="x-name"><a href="Functions.html#TP40014097-CH10-XID_204" data-id="TP40014097-CH10-XID_204">Functions</a></span>.
</p><p class="para">
You write an instance method within the opening and closing braces of the type it belongs to. An instance method has implicit access to all other instance methods and properties of that type. An instance method can be called only on a specific instance of the type it belongs to. It cannot be called in isolation without an existing instance.
</p><p class="para">
Here’s an example that defines a simple <code class="code-voice">Counter</code> class, which can be used to count the number of times an action occurs:
</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">Counter</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">count</span> = <span class="m">0</span></code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">increment</span>() {</code></li>
<li><code class="code-voice"> <span class="vc">count</span>++</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">incrementBy</span>(<span class="vc">amount</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">count</span> += <span class="vc">amount</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">reset</span>() {</code></li>
<li><code class="code-voice"> <span class="vc">count</span> = <span class="m">0</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
The <code class="code-voice">Counter</code> class defines three instance methods:
</p><ul class="list-bullet">
<li class="item"><p class="para">
<code class="code-voice">increment</code> increments the counter by <code class="code-voice">1</code>.
</p>
</li><li class="item"><p class="para">
<code class="code-voice">incrementBy(amount: Int)</code> increments the counter by an specified integer amount.
</p>
</li><li class="item"><p class="para">
<code class="code-voice">reset</code> resets the counter to zero.
</p>
</li>
</ul><p class="para">
The <code class="code-voice">Counter</code> class also declares a variable property, <code class="code-voice">count</code>, to keep track of the current counter value.
</p><p class="para">
You call instance methods with the same dot syntax as 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">counter</span> = <span class="vc">Counter</span>()</code></li>
<li><code class="code-voice"><span class="c">// the initial counter value is 0</span></code></li>
<li><code class="code-voice"><span class="vc">counter</span>.<span class="vc">increment</span>()</code></li>
<li><code class="code-voice"><span class="c">// the counter's value is now 1</span></code></li>
<li><code class="code-voice"><span class="vc">counter</span>.<span class="vc">incrementBy</span>(<span class="m">5</span>)</code></li>
<li><code class="code-voice"><span class="c">// the counter's value is now 6</span></code></li>
<li><code class="code-voice"><span class="vc">counter</span>.<span class="vc">reset</span>()</code></li>
<li><code class="code-voice"><span class="c">// the counter's value is now 0</span></code></li>
</ul>
</div>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_302"></a>
<h3 class="section-name" tabindex="0">Local and External Parameter Names for Methods</h3>
<p class="para">
Function parameters can have both a local name (for use within the function’s body) and an external name (for use when calling the function), as described in <span class="x-name"><a href="Functions.html#TP40014097-CH10-XID_214" data-id="TP40014097-CH10-XID_214">External Parameter Names</a></span>. The same is true for method parameters, because methods are just functions that are associated with a type. However, the default behavior of local names and external names is different for functions and methods.
</p><p class="para">
Methods in Swift are very similar to their counterparts in Objective-C. As in Objective-C, the name of a method in Swift typically refers to the method’s first parameter using a preposition such as <code class="code-voice">with</code>, <code class="code-voice">for</code>, or <code class="code-voice">by</code>, as seen in the <code class="code-voice">incrementBy</code> method from the preceding <code class="code-voice">Counter</code> class example. The use of a preposition enables the method to be read as a sentence when it is called. Swift makes this established method naming convention easy to write by using a different default approach for method parameters than it uses for function parameters.
</p><p class="para">
Specifically, Swift gives the <em>first</em> parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local <em>and</em> external parameter names by default. This convention matches the typical naming and calling convention you will be familiar with from writing Objective-C methods, and makes for expressive method calls without the need to qualify your parameter names.
</p><p class="para">
Consider this alternative version of the <code class="code-voice">Counter</code> class, which defines a more complex form of the <code class="code-voice">incrementBy</code> method:
</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">Counter</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">count</span>: <span class="n"></span> = <span class="m">0</span></code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">incrementBy</span>(<span class="vc">amount</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">count</span> += <span class="vc">amount</span> * <span class="vc">numberOfTimes</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
This <code class="code-voice">incrementBy</code> method has two parameters—<code class="code-voice">amount</code> and <code class="code-voice">numberOfTimes</code>. By default, Swift treats <code class="code-voice">amount</code> as a local name only, but treats <code class="code-voice">numberOfTimes</code> as both a local <em>and</em> an external name. You call the method as follows:
</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">counter</span> = <span class="vc">Counter</span>()</code></li>
<li><code class="code-voice"><span class="vc">counter</span>.<span class="vc">incrementBy</span>(<span class="m">5</span>, <span class="vc">numberOfTimes</span>: <span class="m">3</span>)</code></li>
<li><code class="code-voice"><span class="c">// counter value is now 15</span></code></li>
</ul>
</div>
</section><p class="para">
You don’t need to define an external parameter name for the first argument value, because its purpose is clear from the function name <code class="code-voice">incrementBy</code>. The second argument, however, is qualified by an external parameter name to make its purpose clear when the method is called.
</p><p class="para">
This default behavior effectively treats the method as if you had written a hash symbol (<code class="code-voice">#</code>) before the <code class="code-voice">numberOfTimes</code> parameter:
</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">func</span> <span class="vc">incrementBy</span>(<span class="vc">amount</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">count</span> += <span class="vc">amount</span> * <span class="vc">numberOfTimes</span></code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
The default behavior described above mean that method definitions in Swift are written with the same grammatical style as Objective-C, and are called in a natural, expressive way.
</p>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_303"></a>
<h3 class="section-name" tabindex="0">Modifying External Parameter Name Behavior for Methods</h3>
<p class="para">
Sometimes it’s useful to provide an external parameter name for a method’s first parameter, even though this is not the default behavior. You can either add an explicit external name yourself, or you can prefix the first parameter’s name with a hash symbol to use the local name as an external name too.
</p><p class="para">
Conversely, if you do not want to provide an external name for the second or subsequent parameter of a method, override the default behavior by using an underscore character (<code class="code-voice">_</code>) as an explicit external parameter name for that parameter.
</p>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_304"></a>
<h3 class="section-name" tabindex="0">The self Property</h3>
<p class="para">
Every instance of a type has an implicit property called <code class="code-voice">self</code>, which is exactly equivalent to the instance itself. You use this implicit <code class="code-voice">self</code> property to refer to the current instance within its own instance methods.
</p><p class="para">
The <code class="code-voice">increment</code> method in the example above could have been written like this:
</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">func</span> <span class="vc">increment</span>() {</code></li>
<li><code class="code-voice"> <span class="kt">self</span>.<span class="vc">count</span>++</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
In practice, you don’t need to write <code class="code-voice">self</code> in your code very often. If you don’t explicitly write <code class="code-voice">self</code>, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of <code class="code-voice">count</code> (rather than <code class="code-voice">self.count</code>) inside the three instance methods for <code class="code-voice">Counter</code>.
</p><p class="para">
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the implicit <code class="code-voice">self</code> property to distinguish between the parameter name and the property name.
</p><p class="para">
Here, <code class="code-voice">self</code> disambiguates between a method parameter called <code class="code-voice">x</code> and an instance property that is also called <code class="code-voice">x</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">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"> <span class="kt">func</span> <span class="vc">isToTheRightOfX</span>(<span class="vc">x</span>: <span class="n"></span> {</code></li>
<li><code class="code-voice"> <span class="kt">return</span> <span class="kt">self</span>.<span class="vc">x</span> > <span class="vc">x</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">somePoint</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">5.0</span>)</code></li>
<li><code class="code-voice"><span class="kt">if</span> <span class="vc">somePoint</span>.<span class="vc">isToTheRightOfX</span>(<span class="m">1.0</span>) {</code></li>
<li><code class="code-voice"> <span class="vc">println</span>(<span class="s">"This point is to the right of the line where x == 1.0"</span>)</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="c">// prints "This point is to the right of the line where x == 1.0"</span></code></li>
</ul>
</div>
</section><p class="para">
Without the <code class="code-voice">self</code> prefix, Swift would assume that both uses of <code class="code-voice">x</code> referred to the method parameter called <code class="code-voice">x</code>.
</p>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_305"></a>
<h3 class="section-name" tabindex="0">Modifying Value Types from Within Instance Methods</h3>
<p class="para">
Structures and enumerations are <em>value types</em>. By default, the properties of a value type cannot be modified from within its instance methods.
</p><p class="para">
However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to <em>mutating</em> behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit <code class="code-voice">self</code> property, and this new instance will replace the existing one when the method ends.
</p><p class="para">
You can opt in to this behavior by placing the <code class="code-voice">mutating</code> keyword before the <code class="code-voice">func</code> keyword for that method:
</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">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"> <span class="kt">mutating</span> <span class="kt">func</span> <span class="vc">moveByX</span>(<span class="vc">deltaX</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">x</span> += <span class="vc">deltaX</span></code></li>
<li><code class="code-voice"> <span class="vc">y</span> += <span class="vc">deltaY</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">somePoint</span> = <span class="vc">Point</span>(<span class="vc">x</span>: <span class="m">1.0</span>, <span class="vc">y</span>: <span class="m">1.0</span>)</code></li>
<li><code class="code-voice"><span class="vc">somePoint</span>.<span class="vc">moveByX</span>(<span class="m">2.0</span>, <span class="vc">y</span>: <span class="m">3.0</span>)</code></li>
<li><code class="code-voice"><span class="vc">println</span>(<span class="s">"The point is now at (</span>\(<span class="vc">somePoint</span>.<span class="vc">x</span>)<span class="s">, </span>\(<span class="vc">somePoint</span>.<span class="vc">y</span>)<span class="s">)"</span>)</code></li>
<li><code class="code-voice"><span class="c">// prints "The point is now at (3.0, 4.0)"</span></code></li>
</ul>
</div>
</section><p class="para">
The <code class="code-voice">Point</code> structure above defines a mutating <code class="code-voice">moveByX</code> method, which moves a <code class="code-voice">Point</code> instance by a certain amount. Instead of returning a new point, this method actually modifies the point on which it is called. The <code class="code-voice">mutating</code> keyword is added to its definition to enable it to modify its properties.
</p><p class="para">
Note that you cannot call a mutating method on a constant of structure type, because its properties cannot be changed, even if they are variable properties, as described in <span class="x-name"><a href="Properties.html#TP40014097-CH14-XID_325" data-id="TP40014097-CH14-XID_325">Stored Properties of Constant Structure Instances</a></span>:
</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">fixedPoint</span> = <span class="vc">Point</span>(<span class="vc">x</span>: <span class="m">3.0</span>, <span class="vc">y</span>: <span class="m">3.0</span>)</code></li>
<li><code class="code-voice"><span class="vc">fixedPoint</span>.<span class="vc">moveByX</span>(<span class="m">2.0</span>, <span class="vc">y</span>: <span class="m">3.0</span>)</code></li>
<li><code class="code-voice"><span class="c">// this will report an error</span></code></li>
</ul>
</div>
</section>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_306"></a>
<h3 class="section-name" tabindex="0">Assigning to self Within a Mutating Method</h3>
<p class="para">
Mutating methods can assign an entirely new instance to the implicit <code class="code-voice">self</code> property. The <code class="code-voice">Point</code> example shown above could have been written in the following way instead:
</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">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"> <span class="kt">mutating</span> <span class="kt">func</span> <span class="vc">moveByX</span>(<span class="vc">deltaX</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">self</span> = <span class="vc">Point</span>(<span class="vc">x</span>: <span class="vc">x</span> + <span class="vc">deltaX</span>, <span class="vc">y</span>: <span class="vc">y</span> + <span class="vc">deltaY</span>)</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
This version of the mutating <code class="code-voice">moveByX</code> method creates a brand new structure whose <code class="code-voice">x</code> and <code class="code-voice">y</code> values are set to the target location. The end result of calling this alternative version of the method will be exactly the same as for calling the earlier version.
</p><p class="para">
Mutating methods for enumerations can set the implicit <code class="code-voice">self</code> parameter to be a different member from the same enumeration:
</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">enum</span> <span class="vc">TriStateSwitch</span> {</code></li>
<li><code class="code-voice"> <span class="kt">case</span> <span class="vc">Off</span>, <span class="vc">Low</span>, <span class="vc">High</span></code></li>
<li><code class="code-voice"> <span class="kt">mutating</span> <span class="kt">func</span> <span class="vc">next</span>() {</code></li>
<li><code class="code-voice"> <span class="kt">switch</span> <span class="kt">self</span> {</code></li>
<li><code class="code-voice"> <span class="kt">case</span> <span class="vc">Off</span>:</code></li>
<li><code class="code-voice"> <span class="kt">self</span> = <span class="vc">Low</span></code></li>
<li><code class="code-voice"> <span class="kt">case</span> <span class="vc">Low</span>:</code></li>
<li><code class="code-voice"> <span class="kt">self</span> = <span class="vc">High</span></code></li>
<li><code class="code-voice"> <span class="kt">case</span> <span class="vc">High</span>:</code></li>
<li><code class="code-voice"> <span class="kt">self</span> = <span class="vc">Off</span></code></li>
<li><code class="code-voice"> }</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">ovenLight</span> = <span class="vc">TriStateSwitch</span>.<span class="vc">Low</span></code></li>
<li><code class="code-voice"><span class="vc">ovenLight</span>.<span class="vc">next</span>()</code></li>
<li><code class="code-voice"><span class="c">// ovenLight is now equal to .High</span></code></li>
<li><code class="code-voice"><span class="vc">ovenLight</span>.<span class="vc">next</span>()</code></li>
<li><code class="code-voice"><span class="c">// ovenLight is now equal to .Off</span></code></li>
</ul>
</div>
</section><p class="para">
This example defines an enumeration for a three-state switch. The switch cycles between three different power states (<code class="code-voice">Off</code>, <code class="code-voice">Low</code> and <code class="code-voice">High</code>) every time its <code class="code-voice">next</code> method is called.
</p>
</section>
</section>
<section class="section">
<a name="TP40014097-CH15-XID_307"></a>
<h3 class="section-name" tabindex="0">Type Methods</h3>
<p class="para">
Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called <em>type methods</em>. You indicate type methods for classes by writing the keyword <code class="code-voice">class</code> before the method’s <code class="code-voice">func</code> keyword, and type methods for structures and enumerations by writing the keyword <code class="code-voice">static</code> before the method’s <code class="code-voice">func</code> keyword.
</p><div class="note">
<a name="TP40014097-CH15-XID_308"></a>
<aside class="aside">
<p class="aside-title">Note
</p>
<p class="para">In Objective-C, you can define type-level methods only for Objective-C classes. In Swift, you can define type-level methods for all classes, structures, and enumerations. Each type method is explicitly scoped to the type it supports.
</p>
</aside>
</div><p class="para">
Type methods are called with dot syntax, like instance methods. However, you call type methods on the type, not on an instance of that type. Here’s how you call a type method on a class called <code class="code-voice">SomeClass</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">SomeClass</span> {</code></li>
<li><code class="code-voice"> <span class="kt">class</span> <span class="kt">func</span> <span class="vc">someTypeMethod</span>() {</code></li>
<li><code class="code-voice"> <span class="c">// type method implementation goes here</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="vc">SomeClass</span>.<span class="vc">someTypeMethod</span>()</code></li>
</ul>
</div>
</section><p class="para">
Within the body of a type method, the implicit <code class="code-voice">self</code> property refers to the type itself, rather than an instance of that type. For structures and enumerations, this means that you can use <code class="code-voice">self</code> to disambiguate between static properties and static method parameters, just as you do for instance properties and instance method parameters.
</p><p class="para">
More generally, any unqualified method and property names that you use within the body of a type method will refer to other type-level methods and properties. A type method can call another type method with the other method’s name, without needing to prefix it with the type name. Similarly, type methods on structures and enumerations can access static properties by using the static property’s name without a type name prefix.
</p><p class="para">
The example below defines a structure called <code class="code-voice">LevelTracker</code>, which tracks a player’s progress through the different levels or stages of a game. It is a single-player game, but can store information for multiple players on a single device.
</p><p class="para">
All of the game’s levels (apart from level one) are locked when the game is first played. Every time a player finishes a level, that level is unlocked for all players on the device. The <code class="code-voice">LevelTracker</code> structure uses static properties and methods to keep track of which levels of the game have been unlocked. It also tracks the current level for an individual player.
</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">LevelTracker</span> {</code></li>
<li><code class="code-voice"> <span class="kt">static</span> <span class="kt">var</span> <span class="vc">highestUnlockedLevel</span> = <span class="m">1</span></code></li>
<li><code class="code-voice"> <span class="kt">static</span> <span class="kt">func</span> <span class="vc">unlockLevel</span>(<span class="vc">level</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="kt">if</span> <span class="vc">level</span> > <span class="vc">highestUnlockedLevel</span> { <span class="vc">highestUnlockedLevel</span> = <span class="vc">level</span> }</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">static</span> <span class="kt">func</span> <span class="vc">levelIsUnlocked</span>(<span class="vc">level</span>: <span class="n"></span> {</code></li>
<li><code class="code-voice"> <span class="kt">return</span> <span class="vc">level</span> <= <span class="vc">highestUnlockedLevel</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">currentLevel</span> = <span class="m">1</span></code></li>
<li><code class="code-voice"> <span class="kt">mutating</span> <span class="kt">func</span> <span class="vc">advanceToLevel</span>(<span class="vc">level</span>: <span class="n"></span> {</code></li>
<li><code class="code-voice"> <span class="kt">if</span> <span class="vc">LevelTracker</span>.<span class="vc">levelIsUnlocked</span>(<span class="vc">level</span>) {</code></li>
<li><code class="code-voice"> <span class="vc">currentLevel</span> = <span class="vc">level</span></code></li>
<li><code class="code-voice"> <span class="kt">return</span> <span class="vc">true</span></code></li>
<li><code class="code-voice"> } <span class="kt">else</span> {</code></li>
<li><code class="code-voice"> <span class="kt">return</span> <span class="vc">false</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
The <code class="code-voice">LevelTracker</code> structure keeps track of the highest level that any player has unlocked. This value is stored in a static property called <code class="code-voice">highestUnlockedLevel</code>.
</p><p class="para">
<code class="code-voice">LevelTracker</code> also defines two type functions to work with the <code class="code-voice">highestUnlockedLevel</code> property. The first is a type function called <code class="code-voice">unlockLevel</code>, which updates the value of <code class="code-voice">highestUnlockedLevel</code> whenever a new level is unlocked. The second is a convenience type function called <code class="code-voice">levelIsUnlocked</code>, which returns <code class="code-voice">true</code> if a particular level number is already unlocked. (Note that these type methods can access the <code class="code-voice">highestUnlockedLevel</code> static property without your needing to write it as <code class="code-voice">LevelTracker.highestUnlockedLevel</code>.)
</p><p class="para">
In addition to its static property and type methods, <code class="code-voice">LevelTracker</code> tracks an individual player’s progress through the game. It uses an instance property called <code class="code-voice">currentLevel</code> to track the level that a player is currently playing.
</p><p class="para">
To help manage the <code class="code-voice">currentLevel</code> property, <code class="code-voice">LevelTracker</code> defines an instance method called <code class="code-voice">advanceToLevel</code>. Before updating <code class="code-voice">currentLevel</code>, this method checks whether the requested new level is already unlocked. The <code class="code-voice">advanceToLevel</code> method returns a Boolean value to indicate whether or not it was actually able to set <code class="code-voice">currentLevel</code>.
</p><p class="para">
The <code class="code-voice">LevelTracker</code> structure is used with the <code class="code-voice">Player</code> class, shown below, to track and update the progress of an individual player:
</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">Player</span> {</code></li>
<li><code class="code-voice"> <span class="kt">var</span> <span class="vc">tracker</span> = <span class="vc">LevelTracker</span>()</code></li>
<li><code class="code-voice"> <span class="kt">let</span> <span class="vc">playerName</span>: <span class="n"></span></code></li>
<li><code class="code-voice"> <span class="kt">func</span> <span class="vc">completedLevel</span>(<span class="vc">level</span>: <span class="n"></span>) {</code></li>
<li><code class="code-voice"> <span class="vc">LevelTracker</span>.<span class="vc">unlockLevel</span>(<span class="vc">level</span> + <span class="m">1</span>)</code></li>
<li><code class="code-voice"> <span class="vc">tracker</span>.<span class="vc">advanceToLevel</span>(<span class="vc">level</span> + <span class="m">1</span>)</code></li>
<li><code class="code-voice"> }</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="vc">playerName</span> = <span class="vc">name</span></code></li>
<li><code class="code-voice"> }</code></li>
<li><code class="code-voice">}</code></li>
</ul>
</div>
</section><p class="para">
The <code class="code-voice">Player</code> class creates a new instance of <code class="code-voice">LevelTracker</code> to track that player’s progress. It also provides a method called <code class="code-voice">completedLevel</code>, which is called whenever a player completes a particular level. This method unlocks the next level for all players and updates the player’s progress to move them to the next level. (The Boolean return value of <code class="code-voice">advanceToLevel</code> is ignored, because the level is known to have been unlocked by the call to <code class="code-voice">LevelTracker.unlockLevel</code> on the previous line.)
</p><p class="para">
You can create a instance of the <code class="code-voice">Player</code> class for a new player, and see what happens when the player completes level one:
</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">var</span> <span class="vc">player</span> = <span class="vc">Player</span>(<span class="vc">name</span>: <span class="s">"Argyrios"</span>)</code></li>
<li><code class="code-voice"><span class="vc">player</span>.<span class="vc">completedLevel</span>(<span class="m">1</span>)</code></li>
<li><code class="code-voice"><span class="vc">println</span>(<span class="s">"highest unlocked level is now </span>\(<span class="vc">LevelTracker</span>.<span class="vc">highestUnlockedLevel</span>)<span class="s">"</span>)</code></li>
<li><code class="code-voice"><span class="c">// prints "highest unlocked level is now 2"</span></code></li>
</ul>
</div>
</section><p class="para">
If you create a second player, whom you try to move to a level that is not yet unlocked by any player in the game, the attempt to set the player’s current level fails:
</p><section class="code-listing">
<span class="caption"></span>
<div class="code-sample">
<ul class="code-lines">
<li><code class="code-voice"><span class="vc">player</span> = <span class="vc">Player</span>(<span class="vc">name</span>: <span class="s">"Beto"</span>)</code></li>
<li><code class="code-voice"><span class="kt">if</span> <span class="vc">player</span>.<span class="vc">tracker</span>.<span class="vc">advanceToLevel</span>(<span class="m">6</span>) {</code></li>
<li><code class="code-voice"> <span class="vc">println</span>(<span class="s">"player is now on level 6"</span>)</code></li>
<li><code class="code-voice">} <span class="kt">else</span> {</code></li>
<li><code class="code-voice"> <span class="vc">println</span>(<span class="s">"level 6 has not yet been unlocked"</span>)</code></li>
<li><code class="code-voice">}</code></li>
<li><code class="code-voice"><span class="c">// prints "level 6 has not yet been unlocked"</span></code></li>
</ul>
</div>
</section>
</section>
<section id="next_previous" class="">
<p class="previous-link"><a href="Properties.html#TP40014097-CH14-XID_323" data-id="TP40014097-CH14-XID_323">Properties</a></p>
<p class="next-link"><a href="Subscripts.html#TP40014097-CH16-XID_393" data-id="TP40014097-CH16-XID_393">Subscripts</a></p>
<p class="copyright">Copyright © 2014 Apple Inc. All rights reserved. <a class="link" href="http://www.apple.com/legal/terms/site.html" target="_blank" rel="external">Terms of Use</a> | <a class="link" href="http://www.apple.com/privacy/" target="_blank" rel="external">Privacy Policy</a> | Updated: 2014-06-02
</p>
</section>
</article>
</div>
<div id="big_button"></div>
<footer id="footer">
<div class="content-wrapper">
</div>
<script src="./resource/devpubs-1.1.15.js" type="text/javascript" charset="utf-8"></script> </footer> <div id="blackout"> <div id="preload"></div> </div> </body></html>