-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy path04_Collection_Types.html
897 lines (618 loc) · 47.8 KB
/
04_Collection_Types.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
<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head>
<meta charset="UTF-8">
<title>《The Swift Programming Language》中文版</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="generator" content="GitBook 0.5.2">
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
<link rel="next" href="../chapter2/05_Control_Flow.html" />
<link rel="prev" href="../chapter2/03_Strings_and_Characters.html" />
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.4" data-basepath=".." data-revision="1402903834498">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >The Swift Programming Language 中文版</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i> 序</a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
<a href="../chapter1/chapter1.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
<a href="../chapter1/01_swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
<a href="../chapter1/02_a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
<a href="../chapter2/chapter2.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
<a href="../chapter2/01_The_Basics.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
<a href="../chapter2/02_Basic_Operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本运算符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
<a href="../chapter2/03_Strings_and_Characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
<li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
<a href="../chapter2/04_Collection_Types.html">
<i class="fa fa-check"></i> <b>2.4.</b> 集合类型
</a>
</li>
<li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
<a href="../chapter2/05_Control_Flow.html">
<i class="fa fa-check"></i> <b>2.5.</b> 控制流
</a>
</li>
<li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
<a href="../chapter2/06_Functions.html">
<i class="fa fa-check"></i> <b>2.6.</b> 函数
</a>
</li>
<li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
<a href="../chapter2/07_Closures.html">
<i class="fa fa-check"></i> <b>2.7.</b> 闭包
</a>
</li>
<li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
<a href="../chapter2/08_Enumerations.html">
<i class="fa fa-check"></i> <b>2.8.</b> 枚举
</a>
</li>
<li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
<a href="../chapter2/09_Classes_and_Structures.html">
<i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
</a>
</li>
<li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
<a href="../chapter2/10_Properties.html">
<i class="fa fa-check"></i> <b>2.10.</b> 属性
</a>
</li>
<li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
<a href="../chapter2/11_Methods.html">
<i class="fa fa-check"></i> <b>2.11.</b> 方法
</a>
</li>
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
<a href="../chapter2/12_Subscripts.html">
<i class="fa fa-check"></i> <b>2.12.</b> 下标脚本
</a>
</li>
<li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
<a href="../chapter2/13_Inheritance.html">
<i class="fa fa-check"></i> <b>2.13.</b> 继承
</a>
</li>
<li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
<a href="../chapter2/14_Initialization.html">
<i class="fa fa-check"></i> <b>2.14.</b> 构造过程
</a>
</li>
<li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
<a href="../chapter2/15_Deinitialization.html">
<i class="fa fa-check"></i> <b>2.15.</b> 析构过程
</a>
</li>
<li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
<a href="../chapter2/16_Automatic_Reference_Counting.html">
<i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
</a>
</li>
<li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
<a href="../chapter2/17_Optional_Chaining.html">
<i class="fa fa-check"></i> <b>2.17.</b> 可选链
</a>
</li>
<li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
<a href="../chapter2/18_Type_Casting.html">
<i class="fa fa-check"></i> <b>2.18.</b> 类型检查
</a>
</li>
<li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
<a href="../chapter2/19_Nested_Types.html">
<i class="fa fa-check"></i> <b>2.19.</b> 嵌套类型
</a>
</li>
<li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
<a href="../chapter2/20_Extensions.html">
<i class="fa fa-check"></i> <b>2.20.</b> 扩展
</a>
</li>
<li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
<a href="../chapter2/21_Protocols.html">
<i class="fa fa-check"></i> <b>2.21.</b> 协议
</a>
</li>
<li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
<a href="../chapter2/22_Generics.html">
<i class="fa fa-check"></i> <b>2.22.</b> 泛型
</a>
</li>
<li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
<a href="../chapter2/23_Advanced_Operators.html">
<i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
<a href="../chapter3/chapter3.html">
<i class="fa fa-check"></i> <b>3.</b> 语言参考
</a>
<ul class="articles">
<li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
<a href="../chapter3/01_About_the_Language_Reference.html">
<i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
</a>
</li>
<li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
<a href="../chapter3/02_Lexical_Structure.html">
<i class="fa fa-check"></i> <b>3.2.</b> 词法结构
</a>
</li>
<li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
<a href="../chapter3/03_Types.html">
<i class="fa fa-check"></i> <b>3.3.</b> 类型
</a>
</li>
<li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
<a href="../chapter3/04_Expressions.html">
<i class="fa fa-check"></i> <b>3.4.</b> 表达式
</a>
</li>
<li class="chapter " data-level="3.5" data-path="chapter3/10_Statements.html">
<a href="../chapter3/10_Statements.html">
<i class="fa fa-check"></i> <b>3.5.</b> 语句
</a>
</li>
<li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
<a href="../chapter3/05_Declarations.html">
<i class="fa fa-check"></i> <b>3.6.</b> 声明
</a>
</li>
<li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
<a href="../chapter3/06_Attributes.html">
<i class="fa fa-check"></i> <b>3.7.</b> 特性
</a>
</li>
<li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
<a href="../chapter3/07_Patterns.html">
<i class="fa fa-check"></i> <b>3.8.</b> 模式
</a>
</li>
<li class="chapter " data-level="3.9" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
<i class="fa fa-check"></i> <b>3.9.</b> 泛型参数
</a>
</li>
<li class="chapter " data-level="3.10" data-path="chapter3/09_Summary_of_the_Grammar.html">
<a href="../chapter3/09_Summary_of_the_Grammar.html">
<i class="fa fa-check"></i> <b>3.10.</b> 语法总结
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li><li><p style="padding-left:5px;padding-right:5px;">翻译无任何商业目的,仅供内部学习交流使用!</p></li><li><script src="http://s19.cnzz.com/z_stat.php?id=1000480711&web_id=1000480711" language="JavaScript"></script></li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 57.89473684210526%;min-width: 55.26315789473684%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
<a href="../chapter2/12_Subscripts.html" title="下标脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter done " data-progress="2.13" style="left: 23.68421052631579%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter done " data-progress="2.14" style="left: 26.31578947368421%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter done " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter done " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter done " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter done " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="嵌套类型" class="chapter done " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter done " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter done " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter done " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter done " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter done " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter done " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter done " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter " data-progress="2.5" style="left: 60.526315789473685%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter " data-progress="2.7" style="left: 65.78947368421052%;"></a>
<a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter " data-progress="2.8" style="left: 68.42105263157895%;"></a>
<a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter " data-progress="2.9" style="left: 71.05263157894737%;"></a>
<a href="../chapter3/chapter3.html" title="语言参考" class="chapter new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
<a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter " data-progress="3.1" style="left: 76.3157894736842%;"></a>
<a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter " data-progress="3.10" style="left: 78.94736842105263%;"></a>
<a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter " data-progress="3.2" style="left: 81.57894736842105%;"></a>
<a href="../chapter3/03_Types.html" title="类型" class="chapter " data-progress="3.3" style="left: 84.21052631578948%;"></a>
<a href="../chapter3/04_Expressions.html" title="表达式" class="chapter " data-progress="3.4" style="left: 86.84210526315789%;"></a>
<a href="../chapter3/10_Statements.html" title="语句" class="chapter " data-progress="3.5" style="left: 89.47368421052632%;"></a>
<a href="../chapter3/05_Declarations.html" title="声明" class="chapter " data-progress="3.6" style="left: 92.10526315789474%;"></a>
<a href="../chapter3/06_Attributes.html" title="特性" class="chapter " data-progress="3.7" style="left: 94.73684210526316%;"></a>
<a href="../chapter3/07_Patterns.html" title="模式" class="chapter " data-progress="3.8" style="left: 97.36842105263158%;"></a>
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter " data-progress="3.9" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_96">
<blockquote>
<p>翻译:<a href="https://github.com/zqp" target="_blank">zqp</a><br>校对:<a href="https://github.com/shinyzhu" target="_blank">shinyzhu</a>, <a href="https://github.com/stanzhai" target="_blank">stanzhai</a> </p>
</blockquote>
<h1 id="-collection-types-">集合类型 (Collection Types)</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li><a href="#arrays">数组(Arrays)</a></li>
<li><a href="#dictionaries">字典(Dictionaries)</a></li>
<li><a href="#mutability_of_collections">集合的可变性(Mutability of Collections)</a></li>
</ul>
<p>Swift 语言提供经典的数组和字典两种集合类型来存储集合数据。数组用来按顺序存储相同类型的数据。字典虽然无序存储相同类型数据值但是需要由独有的标识符引用和寻址(就是键值对)。</p>
<p>Swift 语言里的数组和字典中存储的数据值类型必须明确。 这意味着我们不能把不正确的数据类型插入其中。 同时这也说明我们完全可以对获取出的值类型非常自信。 Swift 对显式类型集合的使用确保了我们的代码对工作所需要的类型非常清楚,也让我们在开发中可以早早地找到任何的类型不匹配错误。</p>
<blockquote>
<p>注意:<br>Swift 的数组结构在被声明成常量和变量或者被传入函数与方法中时会相对于其他类型展现出不同的特性。 获取更多信息请参见<a href="#mutability_of_collections">集合的可变性</a>与<a href="09_Classes_and_Structures.html#assignment_and_copy_behavior_for_collection_types">集合在赋值和复制中的行为</a>章节。</p>
</blockquote>
<p><a name="arrays"></a></p>
<h2 id="-">数组</h2>
<p>数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中。</p>
<p>Swift 数组特定于它所存储元素的类型。这与 Objective-C 的 NSArray 和 NSMutableArray 不同,这两个类可以存储任意类型的对象,并且不提供所返回对象的任何特别信息。在 Swift 中,数据值在被存储进入某个数组之前类型必须明确,方法是通过显式的类型标注或类型推断,而且不是必须是<code>class</code>类型。例如: 如果我们创建了一个<code>Int</code>值类型的数组,我们不能往其中插入任何不是<code>Int</code>类型的数据。 Swift 中的数组是类型安全的,并且它们中包含的类型必须明确。</p>
<p><a name="array_type_shorthand_syntax"></a></p>
<h3 id="-">数组的简单语法</h3>
<p>写 Swift 数组应该遵循像<code>Array<SomeType></code>这样的形式,其中<code>SomeType</code>是这个数组中唯一允许存在的数据类型。 我们也可以使用像<code>SomeType[]</code>这样的简单语法。 尽管两种形式在功能上是一样的,但是推荐较短的那种,而且在本文中都会使用这种形式来使用数组。</p>
<p><a name="array_literals"></a></p>
<h3 id="-">数组构造语句</h3>
<p>我们可以使用字面量来进行数组构造,这是一种用一个或者多个数值构造数组的简单方法。字面量是一系列由逗号分割并由方括号包含的数值。
<code>[value 1, value 2, value 3]</code>。</p>
<p>下面这个例子创建了一个叫做<code>shoppingList</code>并且存储字符串的数组:</p>
<pre><code class="lang-swift">var shoppingList: String[] = ["Eggs", "Milk"]
// shoppingList 已经被构造并且拥有两个初始项。
</code></pre>
<p><code>shoppingList</code>变量被声明为“字符串值类型的数组“,记作<code>String[]</code>。 因为这个数组被规定只有<code>String</code>一种数据结构,所以只有<code>String</code>类型可以在其中被存取。 在这里,<code>shoppinglist</code>数组由两个<code>String</code>值(<code>"Eggs"</code> 和<code>"Milk"</code>)构造,并且由字面量定义。</p>
<blockquote>
<p>注意:<br><code>Shoppinglist</code>数组被声明为变量(<code>var</code>关键字创建)而不是常量(<code>let</code>创建)是因为以后可能会有更多的数据项被插入其中。 </p>
</blockquote>
<p>在这个例子中,字面量仅仅包含两个<code>String</code>值。匹配了该数组的变量声明(只能包含<code>String</code>的数组),所以这个字面量的分配过程就是允许用两个初始项来构造<code>shoppinglist</code>。</p>
<p>由于 Swift 的类型推断机制,当我们用字面量构造只拥有相同类型值数组的时候,我们不必把数组的类型定义清楚。 <code>shoppinglist</code>的构造也可以这样写:</p>
<pre><code class="lang-swift">var shoppingList = ["Eggs", "Milk"]
</code></pre>
<p>因为所有字面量中的值都是相同的类型,Swift 可以推断出<code>String[]</code>是<code>shoppinglist</code>中变量的正确类型。</p>
<p><a name="accessing_and_modifying_an_array"></a></p>
<h3 id="-">访问和修改数组</h3>
<p>我们可以通过数组的方法和属性来访问和修改数组,或者下标语法。
还可以使用数组的只读属性<code>count</code>来获取数组中的数据项数量。</p>
<pre><code class="lang-swift">println("The shopping list contains \(shoppingList.count) items.")
// 输出"The shopping list contains 2 items."(这个数组有2个项)
</code></pre>
<p>使用布尔项<code>isEmpty</code>来作为检查<code>count</code>属性的值是否为 0 的捷径。</p>
<pre><code class="lang-swift">if shoppingList.isEmpty {
println("The shopping list is empty.")
} else {
println("The shopping list is not empty.")
}
// 打印 "The shopping list is not empty."(shoppinglist不是空的)
</code></pre>
<p>也可以使用<code>append</code>方法在数组后面添加新的数据项:</p>
<pre><code class="lang-swift">shoppingList.append("Flour")
// shoppingList 现在有3个数据项,有人在摊煎饼
</code></pre>
<p>除此之外,使用加法赋值运算符(<code>+=</code>)也可以直接在数组后面添加数据项:</p>
<pre><code class="lang-swift">shoppingList += "Baking Powder"
// shoppingList 现在有四项了
</code></pre>
<p>我们也可以使用加法赋值运算符(<code>+=</code>)直接添加拥有相同类型数据的数组。</p>
<pre><code class="lang-swift">shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 现在有7项了
</code></pre>
<p>可以直接使用下标语法来获取数组中的数据项,把我们需要的数据项的索引值放在直接放在数组名称的方括号中:</p>
<pre><code class="lang-swift">var firstItem = shoppingList[0]
// 第一项是 "Eggs"
</code></pre>
<p>注意第一项在数组中的索引值是<code>0</code>而不是<code>1</code>。 Swift 中的数组索引总是从零开始。</p>
<p>我们也可以用下标来改变某个已有索引值对应的数据值:</p>
<pre><code class="lang-swift">shoppingList[0] = "Six eggs"
// 其中的第一项现在是 "Six eggs" 而不是 "Eggs"
</code></pre>
<p>还可以利用下标来一次改变一系列数据值,即使新数据和原有数据的数量是不一样的。下面的例子把<code>"Chocolate Spread"</code>,<code>"Cheese"</code>,和<code>"Butter"</code>替换为<code>"Bananas"</code>和 <code>"Apples"</code>:</p>
<pre><code class="lang-swift">shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList 现在有六项
</code></pre>
<blockquote>
<p>注意:<br>我们不能使用下标语法在数组尾部添加新项。如果我们试着用这种方法对索引越界的数据进行检索或者设置新值的操作,我们会引发一个运行期错误。我们可以使用索引值和数组的<code>count</code>属性进行比较来在使用某个索引之前先检验是否有效。除了当<code>count</code>等于 0 时(说明这是个空数组),最大索引值一直是<code>count - 1</code>,因为数组都是零起索引。 </p>
</blockquote>
<p>调用数组的<code>insert(atIndex:)</code>方法来在某个具体索引值之前添加数据项:</p>
<pre><code class="lang-swift">shoppingList.insert("Maple Syrup", atIndex: 0)
// shoppingList 现在有7项
// "Maple Syrup" 现在是这个列表中的第一项
</code></pre>
<p>这次<code>insert</code>函数调用把值为<code>"Maple Syrup"</code>的新数据项插入列表的最开始位置,并且使用<code>0</code>作为索引值。</p>
<p>类似的我们可以使用<code>removeAtIndex</code>方法来移除数组中的某一项。这个方法把数组在特定索引值中存储的数据项移除并且返回这个被移除的数据项(我们不需要的时候就可以无视它):</p>
<pre><code class="lang-swift">let mapleSyrup = shoppingList.removeAtIndex(0)
// 索引值为0的数据项被移除
// shoppingList 现在只有6项,而且不包括Maple Syrup
// mapleSyrup常量的值等于被移除数据项的值 "Maple Syrup"
</code></pre>
<p>数据项被移除后数组中的空出项会被自动填补,所以现在索引值为<code>0</code>的数据项的值再次等于<code>"Six eggs"</code>:</p>
<pre><code class="lang-swift">firstItem = shoppingList[0]
// firstItem 现在等于 "Six eggs"
</code></pre>
<p>如果我们只想把数组中的最后一项移除,可以使用<code>removeLast</code>方法而不是<code>removeAtIndex</code>方法来避免我们需要获取数组的<code>count</code>属性。就像后者一样,前者也会返回被移除的数据项:</p>
<pre><code class="lang-swift">let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
// shoppingList现在只有5项,不包括cheese
// apples 常量的值现在等于"Apples" 字符串
</code></pre>
<p><a name="iterating_over_an_array"></a></p>
<h3 id="-">数组的遍历</h3>
<p>我们可以使用<code>for-in</code>循环来遍历所有数组中的数据项:</p>
<pre><code class="lang-swift">for item in shoppingList {
println(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
</code></pre>
<p>如果我们同时需要每个数据项的值和索引值,可以使用全局<code>enumerate</code>函数来进行数组遍历。<code>enumerate</code>返回一个由每一个数据项索引值和数据值组成的元组。我们可以把这个元组分解成临时常量或者变量来进行遍历:</p>
<pre><code class="lang-swift">for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
</code></pre>
<p>更多关于<code>for-in</code>循环的介绍请参见<a href="05_Control_Flow.html#for_loops">for 循环</a>。</p>
<p><a name="creating_and_initializing_an_array"></a></p>
<h3 id="-">创建并且构造一个数组</h3>
<p>我们可以使用构造语法来创建一个由特定数据类型构成的空数组:</p>
<pre><code class="lang-swift">var someInts = Int[]()
println("someInts is of type Int[] with \(someInts.count) items。")
// 打印 "someInts is of type Int[] with 0 items。"(someInts是0数据项的Int[]数组)
</code></pre>
<p>注意<code>someInts</code>被设置为一个<code>Int[]</code>构造函数的输出所以它的变量类型被定义为<code>Int[]</code>。</p>
<p>除此之外,如果代码上下文中提供了类型信息, 例如一个函数参数或者一个已经定义好类型的常量或者变量,我们可以使用空数组语句创建一个空数组,它的写法很简单:<code>[]</code>(一对空方括号):</p>
<pre><code class="lang-swift">someInts.append(3)
// someInts 现在包含一个INT值
someInts = []
// someInts 现在是空数组,但是仍然是Int[]类型的。
</code></pre>
<p>Swift 中的<code>Array</code>类型还提供一个可以创建特定大小并且所有数据都被默认的构造方法。我们可以把准备加入新数组的数据项数量(<code>count</code>)和适当类型的初始值(<code>repeatedValue</code>)传入数组构造函数:</p>
<pre><code class="lang-swift">var threeDoubles = Double[](count: 3, repeatedValue:0.0)
// threeDoubles 是一种 Double[]数组, 等于 [0.0, 0.0, 0.0]
</code></pre>
<p>因为类型推断的存在,我们使用这种构造方法的时候不需要特别指定数组中存储的数据类型,因为类型可以从默认值推断出来:</p>
<pre><code class="lang-swift">var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
// anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]
</code></pre>
<p>最后,我们可以使用加法操作符(<code>+</code>)来组合两种已存在的相同类型数组。新数组的数据类型会被从两个数组的数据类型中推断出来:</p>
<pre><code class="lang-swift">var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推断为 Double[], 等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
</code></pre>
<p><a name="dictionaries"></a></p>
<h2 id="-">字典</h2>
<p>字典是一种存储多个相同类型的值的容器。每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。和数组中的数据项不同,字典中的数据项并没有具体顺序。我们在需要通过标识符(键)访问数据的时候使用字典,这种方法很大程度上和我们在现实世界中使用字典查字义的方法一样。</p>
<p>Swift 的字典使用时需要具体规定可以存储键和值类型。不同于 Objective-C 的<code>NSDictionary</code>和<code>NSMutableDictionary</code> 类可以使用任何类型的对象来作键和值并且不提供任何关于这些对象的本质信息。在 Swift 中,在某个特定字典中可以存储的键和值必须提前定义清楚,方法是通过显性类型标注或者类型推断。</p>
<p>Swift 的字典使用<code>Dictionary<KeyType, ValueType></code>定义,其中<code>KeyType</code>是字典中键的数据类型,<code>ValueType</code>是字典中对应于这些键所存储值的数据类型。</p>
<p><code>KeyType</code>的唯一限制就是可哈希的,这样可以保证它是独一无二的,所有的 Swift 基本类型(例如<code>String</code>,<code>Int</code>, <code>Double</code>和<code>Bool</code>)都是默认可哈希的,并且所有这些类型都可以在字典中当做键使用。未关联值的枚举成员(参见<a href="08_Enumerations.html">枚举</a>)也是默认可哈希的。</p>
<p><a name="dictionary_literals"></a></p>
<h2 id="-">字典字面量</h2>
<p>我们可以使用字典字面量来构造字典,它们和我们刚才介绍过的数组字面量拥有相似语法。一个字典字面量是一个定义拥有一个或者多个键值对的字典集合的简单语句。</p>
<p>一个键值对是一个<code>key</code>和一个<code>value</code>的结合体。在字典字面量中,每一个键值对的键和值都由冒号分割。这些键值对构成一个列表,其中这些键值对由方括号包含并且由逗号分割:</p>
<pre><code class="lang-swift">[key 1: value 1, key 2: value 2, key 3: value 3]
</code></pre>
<p>下面的例子创建了一个存储国际机场名称的字典。在这个字典中键是三个字母的国际航空运输相关代码,值是机场名称:</p>
<pre><code class="lang-swift">var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
</code></pre>
<p><code>airports</code>字典被定义为一种<code>Dictionary<String, String></code>,它意味着这个字典的键和值都是<code>String</code>类型。</p>
<blockquote>
<p>注意:<br><code>airports</code>字典被声明为变量(用<code>var</code>关键字)而不是常量(<code>let</code>关键字)因为后来更多的机场信息会被添加到这个示例字典中。 </p>
</blockquote>
<p><code>airports</code>字典使用字典字面量初始化,包含两个键值对。第一对的键是<code>TYO</code>,值是<code>Tokyo</code>。第二对的键是<code>DUB</code>,值是<code>Dublin</code>。</p>
<p>这个字典语句包含了两个<code>String: String</code>类型的键值对。它们对应<code>airports</code>变量声明的类型(一个只有<code>String</code>键和<code>String</code>值的字典)所以这个字典字面量是构造两个初始数据项的<code>airport</code>字典。</p>
<p>和数组一样,如果我们使用字面量构造字典就不用把类型定义清楚。<code>airports</code>的也可以用这种方法简短定义:</p>
<pre><code class="lang-swift">var airports = ["TYO": "Tokyo", "DUB": "Dublin"]
</code></pre>
<p>因为这个语句中所有的键和值都分别是相同的数据类型,Swift 可以推断出<code>Dictionary<String, String></code>是<code>airports</code>字典的正确类型。</p>
<p><a name="accessing_and_modifying_a_dictionary"></a></p>
<h3 id="-">读取和修改字典</h3>
<p>我们可以通过字典的方法和属性来读取和修改字典,或者使用下标语法。和数组一样,我们可以通过字典的只读属性<code>count</code>来获取某个字典的数据项数量:</p>
<pre><code class="lang-swift">println("The dictionary of airports contains \(airports.count) items.")
// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)
</code></pre>
<p>我们也可以在字典中使用下标语法来添加新的数据项。可以使用一个合适类型的 key 作为下标索引,并且分配新的合适类型的值:</p>
<pre><code class="lang-swift">airports["LHR"] = "London"
// airports 字典现在有三个数据项
</code></pre>
<p>我们也可以使用下标语法来改变特定键对应的值:</p>
<pre><code class="lang-swift">airports["LHR"] = "London Heathrow"
// "LHR"对应的值 被改为 "London Heathrow
</code></pre>
<p>作为另一种下标方法,字典的<code>updateValue(forKey:)</code>方法可以设置或者更新特定键对应的值。就像上面所示的示例,<code>updateValue(forKey:)</code>方法在这个键不存在对应值的时候设置值或者在存在时更新已存在的值。和上面的下标方法不一样,这个方法返回更新值之前的原值。这样方便我们检查更新是否成功。</p>
<p><code>updateValue(forKey:)</code>函数会返回包含一个字典值类型的可选值。举例来说:对于存储<code>String</code>值的字典,这个函数会返回一个<code>String?</code>或者“可选 <code>String</code>”类型的值。如果值存在,则这个可选值值等于被替换的值,否则将会是<code>nil</code>。</p>
<pre><code class="lang-swift">if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB") {
println("The old value for DUB was \(oldValue).")
}
// 输出 "The old value for DUB was Dublin."(DUB原值是dublin)
</code></pre>
<p>我们也可以使用下标语法来在字典中检索特定键对应的值。由于使用一个没有值的键这种情况是有可能发生的,可选类型返回这个键存在的相关值,否则就返回<code>nil</code>:</p>
<pre><code class="lang-swift">if let airportName = airports["DUB"] {
println("The name of the airport is \(airportName).")
} else {
println("That airport is not in the airports dictionary.")
}
// 打印 "The name of the airport is Dublin Internation."(机场的名字是都柏林国际)
</code></pre>
<p>我们还可以使用下标语法来通过给某个键的对应值赋值为<code>nil</code>来从字典里移除一个键值对:</p>
<pre><code class="lang-swift">airports["APL"] = "Apple Internation"
// "Apple Internation"不是真的 APL机场, 删除它
airports["APL"] = nil
// APL现在被移除了
</code></pre>
<p>另外,<code>removeValueForKey</code>方法也可以用来在字典中移除键值对。这个方法在键值对存在的情况下会移除该键值对并且返回被移除的value或者在没有值的情况下返回<code>nil</code>:</p>
<pre><code class="lang-swift">if let removedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is \(removedValue).")
} else {
println("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin International."
</code></pre>
<p><a name="iterating_over_a_dictionary"></a></p>
<h3 id="-">字典遍历</h3>
<p>我们可以使用<code>for-in</code>循环来遍历某个字典中的键值对。每一个字典中的数据项都由<code>(key, value)</code>元组形式返回,并且我们可以使用临时常量或者变量来分解这些元组:</p>
<pre><code class="lang-swift">for (airportCode, airportName) in airports {
println("\(airportCode): \(airportName)")
}
// TYO: Tokyo
// LHR: London Heathrow
</code></pre>
<p><code>for-in</code>循环请参见<a href="05_Control_Flow.html#for_loops">For 循环</a>。</p>
<p>我们也可以通过访问它的<code>keys</code>或者<code>values</code>属性(都是可遍历集合)检索一个字典的键或者值:</p>
<pre><code class="lang-swift">for airportCode in airports.keys {
println("Airport code: \(airportCode)")
}
// Airport code: TYO
// Airport code: LHR
for airportName in airports.values {
println("Airport name: \(airportName)")
}
// Airport name: Tokyo
// Airport name: London Heathrow
</code></pre>
<p>如果我们只是需要使用某个字典的键集合或者值集合来作为某个接受<code>Array</code>实例 API 的参数,可以直接使用<code>keys</code>或者<code>values</code>属性直接构造一个新数组:</p>
<pre><code class="lang-swift">let airportCodes = Array(airports.keys)
// airportCodes is ["TYO", "LHR"]
let airportNames = Array(airports.values)
// airportNames is ["Tokyo", "London Heathrow"]
</code></pre>
<blockquote>
<p>注意:<br>Swift 的字典类型是无序集合类型。其中字典键,值,键值对在遍历的时候会重新排列,而且其中顺序是不固定的。 </p>
</blockquote>
<p><a name="creating_an_empty_dictionary"></a></p>
<h3 id="-">创建一个空字典</h3>
<p>我们可以像数组一样使用构造语法创建一个空字典:</p>
<pre><code class="lang-swift">var namesOfIntegers = Dictionary<Int, String>()
// namesOfIntegers 是一个空的 Dictionary<Int, String>
</code></pre>
<p>这个例子创建了一个<code>Int, String</code>类型的空字典来储存英语对整数的命名。它的键是<code>Int</code>型,值是<code>String</code>型。</p>
<p>如果上下文已经提供了信息类型,我们可以使用空字典字面量来创建一个空字典,记作<code>[:]</code>(中括号中放一个冒号):</p>
<pre><code class="lang-swift">namesOfIntegers[16] = "sixteen"
// namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// namesOfIntegers 又成为了一个 Int, String类型的空字典
</code></pre>
<blockquote>
<p>注意:<br>在后台,Swift 的数组和字典都是由泛型集合来实现的,想了解更多泛型和集合信息请参见<a href="22_Generics.html">泛型</a>。 </p>
</blockquote>
<p><a name="mutability_of_collections"></a></p>
<h2 id="-">集合的可变性</h2>
<p>数组和字典都是在单个集合中存储可变值。如果我们创建一个数组或者字典并且把它分配成一个变量,这个集合将会是可变的。这意味着我们可以在创建之后添加更多或移除已存在的数据项来改变这个集合的大小。与此相反,如果我们把数组或字典分配成常量,那么它就是不可变的,它的大小不能被改变。</p>
<p>对字典来说,不可变性也意味着我们不能替换其中任何现有键所对应的值。不可变字典的内容在被首次设定之后不能更改。
不可变性对数组来说有一点不同,当然我们不能试着改变任何不可变数组的大小,但是我们可以重新设定相对现存索引所对应的值。这使得 Swift 数组在大小被固定的时候依然可以做的很棒。</p>
<p>Swift 数组的可变性行为同时影响了数组实例如何被分配和修改,想获取更多信息,请参见<a href="09_Classes_and_Structures.html#assignment_and_copy_behavior_for_collection_types">集合在赋值和复制中的行为</a>。</p>
<blockquote>
<p>注意:<br>在我们不需要改变数组大小的时候创建不可变数组是很好的习惯。如此 Swift 编译器可以优化我们创建的集合。 </p>
</blockquote>
</section>
</div>
</div>
</div>
<a href="../chapter2/03_Strings_and_Characters.html" class="navigation navigation-prev " aria-label="Previous page: 字符串和字符"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/05_Control_Flow.html" class="navigation navigation-next " aria-label="Next page: 控制流"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
<script src="http://yandex.st/highlightjs/8.0/styles/default.min.css"></script><script src="http://yandex.st/highlightjs/8.0/highlight.min.js"></script><script text="javascript">$('pre code').each(function(i, block) {hljs.highlightBlock(block);});</script></body>
</html>