forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLangRef.html
2674 lines (2115 loc) · 105 KB
/
LangRef.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Swift Language Reference Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Chris Lattner">
<meta name="description"
content="Swift Language Reference Manual.">
<link rel="stylesheet" href="_static/swift.css" type="text/css">
<script type="text/javascript" src="toc.js"></script>
</head>
<body>
<h1>Swift Language Reference</h1>
<p>
<!-- The Table of Contents is automatically inserted in this <div>.
Do not delete this <div>. -->
<div id="nav"></div>
</p>
<!-- ********************************************************************* -->
<h2 id="decl">Declarations</h2>
<!-- ********************************************************************* -->
<pre class="grammar">
decl ::= <a href="#decl-class">decl-class</a>
decl ::= <a href="#decl-constructor">decl-constructor</a>
decl ::= <a href="#decl-deinit">decl-deinit</a>
decl ::= <a href="#decl-extension">decl-extension</a>
decl ::= <a href="#decl-func">decl-func</a>
decl ::= <a href="#decl-import">decl-import</a>
decl ::= <a href="#decl-enum">decl-enum</a>
decl ::= <a href="#decl-enum-element">decl-enum-element</a>
decl ::= <a href="#decl-protocol">decl-protocol</a>
decl ::= <a href="#decl-struct">decl-struct</a>
decl ::= <a href="#decl-typealias">decl-typealias</a>
decl ::= <a href="#decl-let">decl-let</a>
decl ::= <a href="#decl-var">decl-var</a>
decl ::= <a href="#decl-subscript">decl-subscript</a>
</pre>
<!-- ===================================================================== -->
<h3 id="decl-top-level">Module-Scope Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
top-level ::= <a href="#brace-item-list">brace-item</a>*
</pre>
<p>The top level of a swift source file is grammatically identical to the
contents of a func decl. Some declarations, however, are restricted to
module scope.
</p>
<!-- _____________________________________________________________________ -->
<h4 id="brace-item-list">Brace Enclosed Items</h4>
<pre class="grammar">
brace-item-list ::= '{' brace-item* '}'
brace-item ::= <a href="#decl">decl</a>
brace-item ::= <a href="#expr">expr</a>
brace-item ::= <a href="#stmt">stmt</a>
</pre>
<p>The brace item list provides a sequencing operation which evaluates the
members of its body in order. Function bodies and the bodies of control
flow statements use braces. Also, the <a
href="#decl-top-level">source file</a> itself is effectively a
brace item list, but without the braces.
</p>
<!-- ===================================================================== -->
<h3 id="decl-import">import Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-import ::= <a href="#attribute-list">attribute-list</a> 'import' import-kind? import-path
import-kind ::= 'typealias'
import-kind ::= 'struct'
import-kind ::= 'class'
import-kind ::= 'enum'
import-kind ::= 'protocol'
import-kind ::= 'var'
import-kind ::= 'func'
import-path ::= <a href="#any-identifier">any-identifier</a> ('.' <a href="#any-identifier">any-identifier</a>)*
</pre>
<p>'import' declarations allow named values and types to be accessed with
local names, even when they are defined in other modules and namespaces. See
the section on <a href="#namebind">name binding</a> for more
information on how these work. import declarations are only allowed at
module scope.</p>
<p>'import' directives only impact a single source file: imports in one
swift file do not affect name lookup in another file. import directives can
only occur at the top level of a file, not within a function or namespace.</p>
<p>An import without an explicit import-kind names a module; all of the
module's members are imported into the current scope. The module's name is
also imported into the the current scope in order to allow qualified access
to the module's members, which can be useful for disambiguation.</p>
<p>If an import-kind is provided, the last element of the import path is
taken to be the name of a decl <em>within</em> the module named by the rest of
the path. Only that name is introduced into the current scope; the name of the
module itself is <em>not</em> accessible, nor any other decls within the
module.</p>
<p>Different import-kinds perform different filters on the decls within a
module:</p>
<ul>
<li><code>typealias</code> can be used to import any concrete type (struct,
class, enum, or another typealias). It cannot be used to import protocols,
which are often used for more than just their existential type.</li>
<li><code>struct</code>, <code>class</code>, <code>enum</code> can be used
to import any type whose <i>canonical type</i> is a struct, class,
or enum, respectively. (This allows "Int" to be imported as a struct, for
example, even though its definition in the standard library may be a
typealias for another struct type.)</li>
<li><code>protocol</code> is used to import a protocol</li>
<li><code>var</code> is used to import a module-scoped variable</li>
<li><code>func</code> will import all overloads of a function</li>
</ul>
<pre class="example">
<i>// Import all of the top level symbols and types in a module.</i>
import Swift
<i>// Import a single type.</i>
import typealias Swift.BufferedStream
<i>// Import all addition overloads.</i>
import func Swift.+
</pre>
<!-- ===================================================================== -->
<h3 id="decl-extension">extension Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-extension ::= 'extension' <a href="#type-identifier">type-identifier</a> <a href="#inheritance">inheritance</a>? '{' <a href="#decl">decl</a>* '}'
</pre>
<p>'extension' declarations allow adding member declarations to existing
types, even in other source files and modules. There are different
semantic rules for each type that is extended.
</p>
<!-- _____________________________________________________________________ -->
<h4 id="decl-extension-enum-struct"><a href="#decl-enum">enum</a>, <a
href="#decl-struct">struct</a>, and <a href="#decl-class">class</a>
declaration extensions</h4>
<p>FIXME: Write this section.</p>
<!-- ===================================================================== -->
<h3 id="decl-let">let Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-let ::= <a href="#attribute-list">attribute-list</a> 'let' <a href="#pattern">pattern</a> initializer? (',' pattern initializer?)*
initializer ::= '=' <a href="#expr">expr</a>
</pre>
<p>'let' declarations define an immutable binding between an initializer value
and a name.</p>
<p>Here are some examples of 'let' declarations:</p>
<pre class="example">
<i>// Simple examples.</i>
let a = 4
let c : Int = 42
<i>// This decodes the tuple return value into independently named parts</i>
<i>// and both 'val' and 'err' are in scope after this line.</i>
let (val, err) = foo()
// let declarations require an initializer (though the type is optional).
let b : Int <i>// error: let requires an initializer</i>
// Let bindings of classes make the binding immutable, not the object.
class Rocket {
func blastOff() { ... }
}
let rocket = Rocket()
rocket.blastOff() // okay
rocket = Rocket() <i>// error, cannot change a let binding</i>
</pre>
<!-- "var Declarations" was converted to ReST -->
<!-- ===================================================================== -->
<h3 id="decl-func">func Declarations</h3>
<!-- ===================================================================== -->
<!-- "func Declarations" was converted to ReST -->
<!-- _____________________________________________________________________ -->
<h4 id="func-signature">Function signatures</h4>
<pre class="grammar">
func-signature ::= func-arguments func-signature-result?
func-arguments ::= <a href="#pattern-tuple">pattern-tuple</a>+
func-arguments ::= selector-tuple
<a id="selector-tuple">selector-tuple</a> ::= '(' <a href="#pattern-tuple">pattern-tuple-element</a> ')' (<a href="#identifier">identifier-or-any</a> '(' pattern-tuple-element ')')+
func-signature-result ::= '->' <a href="#type">type</a>
</pre>
<p>A function signature specifies one or more sets of parameter
patterns, plus an optional result type.</p>
<p>When a result type is not written, it is implicitly the empty tuple type,
<tt>()</tt>.</p>
<p>In the body of the function described by a particular signature,
all the variables bound by all of the parameter patterns are in
scope, and the function must return a value of the result type.</p>
<p>An outermost pattern in a function signature must be <a
href="#fully_typed_types">fully-typed</a> and irrefutable. If a result type is
given, it must also be fully-typed.</p>
<p>The type of a function with signature <tt>(P<sub>0</sub>)(P<sub>1</sub>)...(P<sub><i>n</i></sub>) -> R</tt>
is <tt>T<sub>0</sub> -> T<sub>1</sub> -> ... -> T<sub><i>n</i></sub> -> R</tt>,
where <tt>T<sub><i>i</i></sub></tt> is the bottom-up type of the pattern
<tt>P<sub><i>i</i></sub></tt>. This is called "currying". The
behavior of all the intermediate functions (those which do not
return <tt>R</tt>) is to capture their arguments, plus any
arguments from prior patterns, and returns a function which takes
the next set of arguments. When the "uncurried" function is
called (the one taking <tt>T<sub><i>n</i></sub></tt> and returning
<tt>R</tt>), all of the arguments are then available and the
function body is finally evaluated as normal.</p>
<p>A function declared with a selector-style signature
<tt>func(a<sub>0</sub>:T<sub>0</sub>) name<sub>1</sub>(a<sub>1</sub>:T<sub>1</sub>) ... name<sub><i>n</i></sub>(a<sub><i>n</i></sub>:T<sub><i>n</i></sub>) -> R</tt>
has the type <tt>(_:T<sub>0</sub>, name<sub>1</sub>:T<sub>1</sub>, ... name<sub><i>n</i></sub>:T<sub><i>n</i></sub>) -> R</tt>,
that is, the names of the fields in the argument tuple are the
<tt>name<sub><i>n</i></sub></tt> identifiers preceding each argument
pattern. However, in the body of a function
described by a signature, those arguments will be bound using the
corresponding
<tt>a<sub><i>n</i></sub></tt> patterns inside
the arguments. This allows for Cocoa-style keyword function
names such as <tt>doThing(x, withThing:y)</tt> to be defined without
requiring that an awkward keyword name be the same as the
variable name.
<p>Here are some examples of func definitions:</p>
<pre class="example">
<i>// Implicitly returns (), aka <a href="#stdlib-Void">Void</a></i>
func a() {}
<i>// Same as 'a'</i>
func a1() -> Void {}
<i>// Function pointers to a function expression.</i>
var a2 = func ()->() {}
var a3 = func () {}
var a4 = func {}
<i>// Really simple function</i>
func c(arg : Int) -> Int { return arg+4 }
<i>// Simple operators.</i>
func [infix_left=190] + (lhs : Int, rhs : Int) -> Int
func [infix_left=160] == (lhs : Int, rhs : Int) -> Bool
<i>// Curried function with multiple return values:</i>
func d(a : Int) (b : Int) -> (res1 : Int, res2 : Int) {
return (a,b)
}
<i>// A more realistic example on a trivial type.</i>
struct bankaccount {
amount : Int
static func bankaccount() -> bankaccount {
// Custom 'constructor' logic goes here.
}
func deposit(arg : Int) {
amount = amount + arg
}
static func someMetatypeMethod() {}
}
<i>// Dot syntax on metatype.</i>
bankaccount.someMetatypeMethod()
<i>// A function with selector-style signature.</i>
enum PersonOfInterest {
case ColonelMustard
case MissScarlet
}
enum Room {
case Conservatory
case Ballroom
}
enum Weapon {
case Candlestick
case LeadPipe
}
func accuseSuspect(suspect:PersonOfInterest)
inRoom(room:Room)
withWeapon(weapon:Weapon) {
print("It was \(suspect) in the \(room) with the \(weapon)")
}
<i>// Calling a selector-style function.</i>
accuseSuspect(.ColonelMustard, inRoom:.Ballroom, withWeapon:.LeadPipe)
</pre>
<!-- ===================================================================== -->
<h3 id="decl-typealias">typealias Declarations</h3>
<!-- ===================================================================== -->
<div class="commentary">
We use the keyword "typealias" instead of "typedef" because it really is an
alias for an existing type, not a "definition" of a new type.
</div>
<pre class="grammar">
decl-typealias ::= typealias-head '=' <a href="#type">type</a>
<a name="typealias-head"></a>typealias-head ::= 'typealias' <a href="#identifier">identifier</a> <a href="#inheritance">inheritance</a>?
</pre>
<p>'typealias' makes a named alias of a type, like a typedef in C. From that
point on, the alias may be used in all situations the specified name is. If an <a href="#inheritance">inheritance</a> clause is provided, it specifies protocols to which the aliased type shall conform.</p>
<p>Here are some examples of type aliases:</p>
<pre class="example">
<i>// location is an alias for a tuple of ints.</i>
typealias location = (x : Int, y : Int)
<i>// pair_fn is a function that takes two ints and returns a tuple.</i>
typealias pair_fn = (Int) -> (Int) -> (first : Int, second : Int)
</pre>
<!-- ===================================================================== -->
<h3 id="decl-enum">enum Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-enum ::= <a href="#attribute-list">attribute-list</a> 'enum' <a href="#identifier">identifier</a> <a href="#generic-params">generic-params</a>? <a href="#inheritance">inheritance</a>? enum-body
enum-body ::= '{' decl* '}'
decl-enum-element ::= <a href="#attribute-list">attribute-list</a> 'case' enum-case (',' enum-case)*
enum-case ::= <a href="#identifier">identifier</a> <a href="#type-tuple">type-tuple</a>? ('->' <a href="#type">type</a>)?
</pre>
<p>An <tt>enum</tt> declaration creates a <a href="#type-enum">enum type</a>.
Here are some examples of enum declarations:</p>
<pre class="example">
<i>// Declares three enums.</i>
enum DataSearchFlags {
case None
case Backward
case Anchored
}
<i>// Shorthand for the above.</i>
enum DataSearchFlags {
case None, Backward, Anchored
}
<i>// Declare discriminated union with enum decl.</i>
enum SomeInts {
case None
case One(Int)
case Two(Int, Int)
}
func f1(searchpolicy : DataSearchFlags) <i>// DataSearchFlags is a valid type name</i>
func test1() {
f1(DataSearchFlags.None) <i>// Use of constructor with qualified identifier</i>
f1(.None) <i>// Use of constructor with context sensitive type inference</i>
<i>// "None" has no type argument, so the constructor's type is "DataSearchFlags".</i>
var a : DataSearchFlags = .None
}
enum SomeMoreInts {
case None <i>// Doesn't conflict with previous "None".</i>
case One(Int)
case Two(Int, Int)
}
func f2(a : SomeMoreInts)
func test2() {
<i>// Constructors for enum element can be used in the obvious way.</i>
f2(.None)
f2(.One(4))
f2(.Two(1, 2))
<i>// Constructor for None has type "SomeMoreInts".</i>
var a : SomeMoreInts = SomeMoreInts.None
<i>// Constructor for One has type "(Int) -> SomeMoreInts".</i>
var b : (Int) -> SomeMoreInts = SomeMoreInts.One
<i>// Constructor for Two has type "(Int,Int) -> SomeMoreInts".</i>
var c : (Int,Int) -> SomeMoreInts = SomeMoreInts.Two
}
</pre>
<!-- ===================================================================== -->
<h3 id="decl-struct">struct Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-struct ::= <a href="#attribute-list">attribute-list</a> 'struct' <a href="#identifier">identifier</a> <a href="#generic-params">generic-params</a>? <a href="#inheritance">inheritance</a>? '{' decl-struct-body '}'
decl-struct-body ::= <a href="#decl">decl</a>*
</pre>
<p>A struct declares a simple value type that can contain data members and
have methods.</p>
<p>The body of a 'struct' is a list of decls. Stored (non-computed) 'var'
decls declare members with storage in the struct. Other declarations act
like they would in an <a href="#decl-extension">extension</a> of the
struct type.</p>
<p>Here are a few simple examples:</p>
<pre class="example">
struct S1 {
var a : Int, b : Int
}
struct S2 {
var a : Int
func f() -> Int { return b }
var b : Int
}
</pre>
<p>Here are some more realistic examples of structs:</p>
<pre class="example">
struct Point { x : Int, y : Int }
struct Size { width : Int, height : Int }
struct Rect {
origin : Point,
size : Size
typealias CoordinateType = Int
func area() -> Int { return size.width*size.height }
}
func test4() {
var a : Point
var b = Point.Point(1, 2) // Silly but fine.
var c = Point(y = 1, x = 2) // Using metatype.
var x1 = Rect(a, Size(42, 123))
var x2 = Rect(size = Size(width = 42, height=123), origin = a)
var x1_area = x1.width*x1.height
var x1_area2 = x1.area()
}
</pre>
<div class="commentary">
Structs do not support inheritance due to undesirable ripple effects across
the design of the language. For example, method dispatch would arguably need
to become virtual, not static. The storage of the type would arguably need
to become indirected so that an array of T could be implemented sanely
(because we don't know if T is actually a T, or a subclass of T). We'd need
to store the "isa"/vtable in the struct so that virtual method dispatch
could be implemented, and this has additional storage costs. None of these
tradeoffs make sense for the intended use cases we have in mind for structs
(Ints, Floats, Points, Rects, UUIDs, IP addresses, C struct interop, etc,
etc). Said differently: we're trying to force a hard wall
between types that need indirect access by their nature and those types
that need direct access by their nature. The former are called classes. The
latter are called structs.
</div>
<!-- ===================================================================== -->
<h3 id="decl-class">class Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-class ::= <a href="#attribute-list">attribute-list</a> 'class' <a href="#identifier">identifier</a> <a href="#generic-params">generic-params</a>? <a href="#inheritance">inheritance</a>? '{' decl-class-body '}'
decl-class-body ::= <a href="#decl">decl</a>*
</pre>
<p>A class declares a reference type referring to an object which can contain
data members and have methods. Classes support single inheritance;
a parent class should be listed as the first type in the
inheritance list.</p>
<p>The body of a 'class' is a list of decls. Stored (non-computed) 'var' decls
declare members with storage in the class. Non-type 'var' and 'func'
decls declare instance members;type 'var' and 'func' decls declare
members of the class itself. Both class and instance members can
be overridden by a subclass.</p>
<p>Type declarations inside a class act essentially the same way as type
declarations outside a class.</p>
<p>FIXME: For the moment, see classes.rst for more details on the
class system.</p>
<p>FIXME: Add a reference to the section on generics.</p>
<p>The only way to create a new instance of a class is with a
call to one of the class's constructors.</p>
<p>Here is a simple example:</p>
<pre class="example">
class C1 {
var a : Int
var b : Int
}
</pre>
<!-- ===================================================================== -->
<h3 id="decl-protocol">Protocol Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-protocol ::= <a href="#attribute-list">attribute-list</a> 'protocol' <a href="#identifier">identifier</a> <a href="#inheritance">inheritance</a>? '{' protocol-member* '}'
</pre>
<p>A protocol declaration describes an abstract interface implemented by
another type. It consists of a set of declarations, which may be instance
methods or properties. A type <i>conforms</i> to a protocol if it
provides declarations that correspond to each of the declarations in
a protocol.</p>
<p>Here are some examples of protocols:</p>
<pre class="example">
protocol Document {
var title : String
}
</pre>
<!-- _____________________________________________________________________ -->
<h4 id="protocol-member-func">'func' protocol elements</h4>
<pre class="grammar">
protocol-member ::= <a href="#decl-func">decl-func</a>
</pre>
<p>'func' members of a protocol define a value of function type that may be
accessed with dot syntax on a value of the protocol's type. The function
gets an implicit "self" argument of the protocol type or (for a type
function) of the metatype of the protocol.</p>
<!-- _____________________________________________________________________ -->
<h4 id="protocol-member-var">'var' protocol elements</h4>
<pre class="grammar">
protocol-member ::= <a href="#decl-var">decl-var</a>
</pre>
<p>'var' members of a protocol define "property" values that may be accessed
with dot syntax on a value of the protocol's type. The actual
variables may have no storage, and will always be accessed by a getter
and setter. Thus, the variables shall have neither an initializer
nor a getter/setter clause.</p>
<!-- _____________________________________________________________________ -->
<h4 id="protocol-member-subscript">'subscript' protocol elements</h4>
<pre class="grammar">
protocol-member ::= <a href="#subscript-head">subscript-head</a>
</pre>
<p>'subscript' members of a protocol define subscripting operations
that may be accessed with the subscript operator ('[]') applied to a
value of the protocol's type. </p>
<div class="commentary">
TODO: There is currently no way to express a requirement for a
read-only or write-only subscript operation or variable. We may
end up doing this with some kind of 'const' or 'immutable'
attribute.
</div>
<!-- _____________________________________________________________________ -->
<h4 id="protocol-member-typealias">'typealias' protocol elements (associated types)</h4>
<pre class="grammar">
protocol-member ::= <a href="#typealias-head">typealias-head</a> ('=' <a href="#type">type</a>)?
</pre>
<p>'typealias' members of a protocol define associated types, which
are types used within the description of a protocol (typically in
the inputs and outputs of 'func' members) that vary from one
conforming type to another. When an associated type has an <a
href="#inheritance">inheritance</a> clause, any type meant to
satisfy the associated type requirement must conform to each of the
protocols specified within that inheritance clause. If a type is
provided after the '=', it is a default definition for the
associated type that will be used as the type witness if the type
witness cannot be determined in any other way.</p>
<pre class="example">
protocol SequenceType {
typename Generator : GeneratorType
func generate() -> Generator
}
</pre>
<!-- "subscript Declarations" was converted to ReST -->
<!-- ===================================================================== -->
<h3 id="decl-constructor">constructor Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-constructor ::= <a href="#attribute-list">attribute-list</a> 'init' <a href="#generic-params">generic-params</a>? constructor-signature <a href="#brace-item-list">brace-item-list</a>
constructor-signature ::= <a href="#pattern-tuple">pattern-tuple</a> constructor-result?
constructor-signature ::= <a href="#identifier">identifier-or-any</a> <a href="#selector-tuple">selector-tuple</a> constructor-result?
constructor-result ::= '->' 'Self'
</pre>
<p>'constructor' declares a constructor for a class, struct, or enum. Such
a declaration is used whenever an object is constructed. Specifically,
for classes, it is used when a new expression is written, and for structs
and enums, it is used for function application when the "function"
is a metatype.</p>
<p>FIXME: We haven't decided the precise rules for when constructors are
implicitly declared. Default construction doesn't work right for structs
or enums. We haven't decided what the restrictions are if a member
isn't default-constructible.</p>
<p>A simple example:</p>
<pre class="example">
struct X {
var member : Int
init(x : Int) {
member = x
}
}
var a = X(10)
</pre>
<p>If a class is derived from a superclass, it must explicitly invoke a
superclass constructor using the <tt>super.init</tt> syntax.
<tt>super.init</tt> may only be used in a subclass constructor;
it is not valid in a struct, enum, or root class constructor. Additionally,
<tt>super.init</tt> may only be referenced exactly once per derived
constructor. An example:</p>
<pre class="example">
class View {
var bounds : Rect
init(bounds:Rect) {
self.bounds = bounds
}
}
class Button : View {
var onClick : () -> ()
init(bounds:Rect, onClick:() -> ()) {
super.init(bounds)
self.onClick = onClick
}
}
</pre>
<!-- ===================================================================== -->
<h3 id="decl-deinit">deinitializer Declarations</h3>
<!-- ===================================================================== -->
<pre class="grammar">
decl-deinit ::= <a href="#attribute-list">attribute-list</a> 'deinit' <a href="#brace-item-list">brace-item-list</a>
</pre>
<p>'deinit' declares a deinitializer for a class. This function is called
when there are no longer any references to a class object, just before it
is destroyed. Note that deinitializers can only be declared for classes,
and cannot be declared in extensions. Subclass deinitializers implicitly
invoke their superclass deinitializers after executing.</p>
<p>FIXME: We haven't really decided the precise rules here, but it's probably
a fatal error to either throw an exception or stash a reference to 'self'
in a deinitializer. Not sure what happens when we cause the reference count
of another object to reach zero inside a deinitializer. We might eventually
allow deinitializers in extensions once we have ivars in extensions.</p>
<p>A simple example:</p>
<pre class="example">
class X {
var fd : Int
deinit {
close(fd)
}
}
</pre>
<!-- ===================================================================== -->
<h3 id="attribute-list">Attribute Lists</h3>
<!-- ===================================================================== -->
<pre class="grammar">
attribute-list ::= /*empty*/
attribute-list ::= attribute-list-clause attribute-list
attribute-list-clause ::= '@' attribute
attribute-list-clause ::= '@' attribute ','? attribute-list-clause
attribute ::= attribute-infix
attribute ::= attribute-resilience
attribute ::= attribute-inout
attribute ::= attribute-autoclosure
attribute ::= attribute-noreturn
</pre>
<p>An attribute list is written as a sequence of attributes, each of which has
a leading '@' sign. Attributes can be optionally comma separated.
Attributes may not be repeated within a list.</p>
<!-- _____________________________________________________________________ -->
<h4 id="attribute-infix">Infix Attributes</h4>
<pre class="grammar">
attribute-infix ::= 'infix_left' '=' <a href="#integer_literal">integer_literal</a>
attribute-infix ::= 'infix_right' '=' <a href="#integer_literal">integer_literal</a>
attribute-infix ::= 'infix '=' <a href="#integer_literal">integer_literal</a>
</pre>
<p>The infix attributes may only be applied to the declaration of a
function of binary operator type whose name is an
<a href="#operator"><tt>operator</tt></a>. The name indicates the
associativity of the operator, either left associative, right associative, or
non-associative.</p>
<p>FIXME: Implement these restrictions.</p>
<!-- _____________________________________________________________________ -->
<h4 id="attribute-resilence">Resilience Attribute</h4>
<pre class="grammar">
attribute-resilience ::= 'resilient'
attribute-resilience ::= 'fragile'
attribute-resilience ::= 'born_fragile'
</pre>
<p>See the resilience design.</p>
<!-- _____________________________________________________________________ -->
<h4 id="attribute-inout"><tt>inout</tt> Attribute</h4>
<pre class="grammar">
attribute-inout ::= 'inout'
</pre>
<p><tt>inout</tt> is only valid in a <tt>type</tt> that
appears within either a <a href="#pattern"><tt>pattern</tt></a> of
a <tt>function-signature</tt> or the input type of a function
type.
</p>
<p><tt>inout</tt> indicates that the argument will be passed as an "in-out"
parameter. The caller must pass an lvalue decorated with the <tt>&</tt>
prefix operator as the argument. Semantically, the value of the argument
is passed "in" to the callee to a local value, and that local value is
stored back "out" to the lvalue when the callee exits. This is normally
indistinguishable from pass-by-reference semantics.</p>
<p><tt>inout</tt> differs from traditional pass-by-reference when closures
are involved. If a closure captures an <tt>inout</tt> parameter, the
<em>local value</em> is captured, not the reference. The local value at
the time of function exit is written back to the lvalue.
If the closure outlives the lifetime of the call, the local value lives
independent of the original lvalue; further mutations within the closure
do not affect the lvalue that was passed as the byref argument.
For example, the following code:
<pre class=example>
func foo(inout x: Int) -> () -> Int {
func bar() -> Int {
x += 1
return x
}
// Call 'bar' once while the inout is active.
bar()
return bar
}
var x = 219
var f = foo(&x)
// x is updated to the value of foo's local x at function exit.
print("global x = \(x)")
// These calls only update the captured local 'x', which is now independent
// of the inout parameter.
print("local x = \(f())")
print("local x = \(f())")
print("local x = \(f())")
print("global x = \(x)")
</pre>
will print:
<pre class=example>
global x = 220
local x = 221
local x = 222
local x = 223
global x = 220
</pre>
<p>The type being annotated must be <a href="#materializable">materializable</a>.
The type after annotation is never materializable.</tt>
<p>FIXME: we probably need a const-like variant, which permits
r-values (and avoids writeback when the l-value is not physical).
We may also need some way of representing <q>this will be
consumed by the nth curry</q>.
</p>
<!-- _____________________________________________________________________ -->
<h4 id="attribute-autoclosure">autoclosure Attribute</h4>
<pre class="grammar">
attribute-autoclosure ::= 'autoclosure'
</pre>
<p>The <tt>autoclosure</tt> attribute modifies a <a
href="#type-function">function type</a>, changing the behavior of any
assignment into (or initialization of) a value with the function type.
Instead of requiring that the rvalue and lvalue have the same function type,
an "auto closing" function type requires its initializer expression to have
the same type as the function's result type, and it implicitly binds a
closure over this expression. This is typically useful for function arguments
that want to capture computation that can be run lazily.</p>
<p><tt>autoclosure</tt> is only valid in a <tt>type</tt> of a
syntactic function type that is defined to take a syntactic empty tuple.
</p>
<pre class="example">
<i>// An auto closure value. This captures an implicit closure over the</i>
<i>// specified expression, instead of the expression itself.</i>
var a : @autoclosure () -> Int = 4
<i>// Definition of an 'assert' function. Assertions and logging routines</i>
<i>// often want to conditionally evaluate their argument.</i>
func assert(condition : @autoclosure () -> Bool)
<i>// Definition of the || operator - it captures its right hand side as</i>
<i>// an autoclosure so it can short-circuit evaluate it.</i>
func [infix_left=110] || (lhs: Bool, rhs: @autoclosure ()->Bool) -> Bool
<i>// Example uses of these functions:</i>
assert(i < j)
if (a == 0 || b == 42) { ... }
</pre>
<!-- _____________________________________________________________________ -->
<h4 id="attribute-noreturn">No Return Attribute</h4>
<pre class="grammar">
attribute-noreturn ::= 'noreturn'
</pre>
<p>Attribute <tt>noreturn</tt> is only valid in the attribute list of a
function declaration or in the attribute list of a <tt>type</tt>
that describes a syntactic function type.
</p>
<p><tt>noreturn</tt> indicates to the compiler that the function will not
return to the caller. This attribute should be used to suppress the
uninitialized variable, missing return warnings and errors. The compiler is
also allowed to more aggressively optimize the code in presence of this
attribute.
</p>
<p>If a function with no a <tt>noreturn</tt> attribute contains a
<tt>return</tt> statement, an error will be raised.
</p>
<!-- ********************************************************************* -->
<h2 id="type">Types</h2>
<!-- ********************************************************************* -->
<pre class="grammar">
type ::= <a href="#attribute-list">attribute-list</a> <a href="#type-function">type-function</a>
type ::= <a href="#attribute-list">attribute-list</a> <a href="#type-array">type-array</a>
type-simple ::= <a href="#type-identifier">type-identifier</a>
type-simple ::= <a href="#type-tuple">type-tuple</a>
type-simple ::= <a href="#type-composition">type-composition</a>
type-simple ::= <a href="#type-metatype">type-metatype</a>
type-simple ::= <a href="#type-optional">type-optional</a>
</pre>
<p>Swift has a small collection of core datatypes that are built into the
compiler. Most user-facing datatypes are defined by the
<a href="#stdlib">standard library</a> or declared as a user defined
types.</p>
<!-- _____________________________________________________________________ -->
<h3>Metatypes</h3>
<p id="metatype">Each type has a corresponding <i>metatype</i>, with the same
name as the type, that is injected into the standard name lookup scope when
a type is <a href="#decl">declared</a>. This allows access to '<a
href="#decl-func">static functions</a>' through dot syntax. For example:</p>
<pre class="example">
// Declares a type 'foo' as well as its metatype.
struct foo {
static func bar() {}
}
// Declares x to be of type foo. A reference to a name in type context
// refers to the type itself.
var x : foo
// Accesses a static function on the foo metatype. In a value context, the
// name of its type refers to its metatype.
foo.bar()
</pre>
<!-- _____________________________________________________________________ -->
<h3 id="fully_typed_types">Fully-Typed Types</h3>
<p>A type may be <i>fully-typed</i>. A type is fully-typed <i>unless</i> one
of the following conditions hold:</p>
<ol>
<li>It is a function type whose result or input type is not
fully-typed.</li>
<li>It is a tuple type with an element that is not
fully-typed. A tuple element is fully-typed unless it has no
explicit type (which is permitted for defaultable elements) or its
explicit type is not fully-typed. In other words, a type is
fully-typed unless it syntactically contains a tuple element with
no explicit type annotation.</li>
</ol>
<p>A type being 'fully-typed' informally means that the type is specified
directly from its type annotation without needing contextual or other
information to resolve its type.</p>
<!-- _____________________________________________________________________ -->
<h3>Materializable Types</h3>
<p id="materializable">A type may be <i>materializable</i>. A type
is materializable unless it is 1) annotated with
a <a href="#attribute-inout"><tt>inout</tt></a> attribute or 2) a
tuple with a non-materializable element type. In general, variables
must have materializable type.</p>
<!-- ===================================================================== -->
<h3 id="type-identifier">Named Types</h3>
<!-- ===================================================================== -->
<pre class="grammar">
type-identifier ::= type-identifier-component ('.' type-identifier-component)*
type-identifier-component ::= <a href="#identifier">identifier</a> <a href="#generic-args">generic-args</a>?
</pre>
<p>Named types may be used simply by using their name. Named types are
introduced by <a href="#decl-typealias">typealias</a> declarations or
through type declarations that expand to one.</p>
<pre class="example">
typealias location = (x : Int, y : Int)
var x : location <i>// use of a named type.</i>
</pre>