KM的博客.

Swift标准库源码

字数统计: 8.5k阅读时长: 50 min
2020/04/18

Swift标准库源码

如何阅读 Swift 标准库中的源码 | Swift源码地址

00关键词

Algorithm源码

min()

1
2
3
4
5
6
7
8
9
10
11
12
13
public func min<T: Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y` we pick `x`.
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
return y < x ? y : x
}
public func min<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var minValue = min(min(x, y), z)
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
for value in rest where value < minValue {
minValue = value
}
return minValue
}

max()

1
2
3
4
5
6
7
8
9
10
11
12
13
public func max<T: Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y`, we pick `y`. See min(_:_:).
return y >= x ? y : x
}

public func max<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var maxValue = max(max(x, y), z)
// In case `value == maxValue`, we pick `value`. See min(_:_:).
for value in rest where value >= maxValue {
maxValue = value
}
return maxValue
}

EnumeratedSequence

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
public struct EnumeratedSequence<Base: Sequence> {
internal var _base: Base
internal init(_base: Base) {
self._base = _base
}
}

extension EnumeratedSequence {
/// var iterator = ["foo", "bar"].enumerated().makeIterator()
/// iterator.next() // (0, "foo")
/// iterator.next() // (1, "bar")
/// iterator.next() // nil
/// To create an instance, call `enumerated().makeIterator()` on a sequence or collection.
public struct Iterator {
internal var _base: Base.Iterator
internal var _count: Int
internal init(_base: Base.Iterator) {
self._base = _base
self._count = 0
}
}
}

extension EnumeratedSequence.Iterator: IteratorProtocol, Sequence {
/// The type of element returned by `next()`.
public typealias Element = (offset: Int, element: Base.Element)

public mutating func next() -> Element? {
guard let b = _base.next() else { return nil }
let result = (offset: _count, element: b)
_count += 1
return result
}
}

extension EnumeratedSequence: Sequence {
/// Returns an iterator over the elements of this sequence.
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator())
}
}

Sequence源码

IteratorProtocol

1
2
3
4
public protocol IteratorProtocol {
associatedtype Element
mutating func next() -> Element?
}

“序列和迭代器非常相似,你可能会问,为什么它们会被分为不同的类型?为什么不能直接把 IteratorProtocol 的功能包含到 Sequence 中呢?”

1
2
3
4
5
6
7
8
func fibsIterator() -> AnyIterator<Int> {
var state = (0, 1)
return AnyIterator {
let upcomingNumber = state.0
state = (state.1, state.0 + state.1)
return upcomingNumber
}
}

Sequence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public protocol Sequence {

associatedtype Element

associatedtype Iterator: IteratorProtocol where Iterator.Element == Element

__consuming func makeIterator() -> Iterator

var underestimatedCount: Int { get }

func _customContainsEquatableElement(
_ element: Element
) -> Bool?

__consuming func _copyToContiguousArray() -> ContiguousArray<Element>

__consuming func _copyContents(
initializing ptr: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index)

func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R?
}

Sequence实现

map()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
extension Sequence {

@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)

var iterator = self.makeIterator()

// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}
}

filter()

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
extension Sequence {
@inlinable
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}

@_transparent
public func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {

var result = ContiguousArray<Element>()

var iterator = self.makeIterator()

while let element = iterator.next() {
if try isIncluded(element) {
result.append(element)
}
}

return Array(result)
}
}

forEach()

1
2
3
4
5
6
7
8
9
10
11
12
extension Sequence {
@_semantics("sequence.forEach")
@inlinable
public func forEach(
_ body: (Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}

split()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension Sequence where Element: Equatable {
@inlinable
public __consuming func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [ArraySlice<Element>] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}

IteratorSequence()

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
public struct IteratorSequence<Base: IteratorProtocol> {
@usableFromInline
internal var _base: Base

/// Creates an instance whose iterator is a copy of `base`.
@inlinable
public init(_ base: Base) {
_base = base
}
}

extension IteratorSequence: IteratorProtocol, Sequence {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable
public mutating func next() -> Base.Element? {
return _base.next()
}
}

SequenceAlgorithms源码

enumerated()

1
2
3
4
5
6
7
extension Sequence {
@inlinable // protocol-only
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}


min()

1
2
3
4
5
6
7
8
9
10
11
12
13
extension Sequence {
public func min(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(e, result) { result = e }
}
return result
}
}

max()

1
2
3
4
5
6
7
8
9
10
11
12
13
extension Sequence {
public func max(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(result, e) { result = e }
}
return result
}
}

contains()

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
extension Sequence {
@inlinable
public func contains(
where predicate: (Element) throws -> Bool
) rethrows -> Bool {
for e in self {
if try predicate(e) {
return true
}
}
return false
}

@inlinable
public func allSatisfy(
_ predicate: (Element) throws -> Bool
) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}
extension Sequence where Element: Equatable {
@inlinable
public func contains(_ element: Element) -> Bool {
if let result = _customContainsEquatableElement(element) {
return result
} else {
return self.contains { $0 == element }
}
}
}

reduce()函数

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
extension Sequence {
@inlinable
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult:
(_ partialResult: Result, Element) throws -> Result
) rethrows -> Result {
var accumulator = initialResult
for element in self {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}

@inlinable
public func reduce<Result>(
into initialResult: __owned Result,
_ updateAccumulatingResult:
(_ partialResult: inout Result, Element) throws -> ()
) rethrows -> Result {
var accumulator = initialResult
for element in self {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
}

reversed()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension Sequence {

@inlinable
public __consuming func reversed() -> [Element] {

var result = Array(self)
let count = result.count
for i in 0..<count/2 {
result.swapAt(i, count - ((i + 1) as Int))
}
return result
}
}

flatMap()

1
2
3
4
5
6
7
8
9
10
11
12
13
extension Sequence {
@inlinable
public func flatMap<SegmentOfResult: Sequence>(
_ transform: (Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] {
var result: [SegmentOfResult.Element] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
}

03 zip源码

zip使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let words = ["one", "two", "three", "four"]
let numbers = ["1", "2", "3", "4", "5", "6"]
// 1.1、Array(zip())生成元组
let arr = Array(zip(words, numbers))
//1.2、zip+map生成元组
let a = zip(words, numbers).map { $0 }
print(a)//"[("one", "1"), ("two", "2"), ("three", "3"), ("four", "4")]\n"

//2、将两个数组合并成一个新数组
let b = [words, numbers].flatMap { $0 }
print(b)//"["one", "two", "three", "four", "1", "2", "3", "4", "5", "6"]\n"

let c = zip(words, numbers).flatMap { [$0, $1] }
print(c) // "["one", "1", "two", "2", "three", "3", "four", "4"]\n"

//3、将两个数组生成字典
let dic = Dictionary(uniqueKeysWithValues: zip(words, numbers))
print(dic)//["two": "2", "four": "4", "one": "1", "three": "3"]

zip源码

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
public func zip<Sequence1, Sequence2>(
_ sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
return Zip2Sequence(sequence1, sequence2)
}

@frozen // generic-performance
public struct Zip2Sequence<Sequence1: Sequence, Sequence2: Sequence> {
@usableFromInline // generic-performance
internal let _sequence1: Sequence1
@usableFromInline // generic-performance
internal let _sequence2: Sequence2

@inlinable // generic-performance
internal init(_ sequence1: Sequence1, _ sequence2: Sequence2) {
(_sequence1, _sequence2) = (sequence1, sequence2)
}
}

extension Zip2Sequence {
/// An iterator for `Zip2Sequence`.
@frozen // generic-performance
public struct Iterator {
@usableFromInline // generic-performance
internal var _baseStream1: Sequence1.Iterator
@usableFromInline // generic-performance
internal var _baseStream2: Sequence2.Iterator
@usableFromInline // generic-performance
internal var _reachedEnd: Bool = false

@inlinable // generic-performance
internal init(
_ iterator1: Sequence1.Iterator,
_ iterator2: Sequence2.Iterator
) {
(_baseStream1, _baseStream2) = (iterator1, iterator2)
}
}
}


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
extension Zip2Sequence.Iterator: IteratorProtocol {
public typealias Element = (Sequence1.Element, Sequence2.Element)

@inlinable // generic-performance
public mutating func next() -> Element? {
if _reachedEnd {
return nil
}

guard let element1 = _baseStream1.next(),
let element2 = _baseStream2.next() else {
_reachedEnd = true
return nil
}

return (element1, element2)
}
}

extension Zip2Sequence: Sequence {
public typealias Element = (Sequence1.Element, Sequence2.Element)

/// Returns an iterator over the elements of this sequence.
@inlinable // generic-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator())
}

@inlinable // generic-performance
public var underestimatedCount: Int {
return Swift.min(
_sequence1.underestimatedCount,
_sequence2.underestimatedCount
)
}

04

05

06

07

08

09

10

集合协议Sequence: 如果让你设计Sequence类型,你会为它添加那些约束呢?如果你没有特别丰富的经验,最好的办法,还是去看看Swift官方的Sequence实现吧。还是那句话,源码之前,了无秘密。

Sequence是一个值类型

当我们走近源代码之前,先来思考一个问题。一个最纯粹的“序列”,究竟意味着什么呢?通过前面两节内容我们知道,序列本身可以是有限的,也可以是无限的;可以是支持多次遍历的,也可以是只能遍历一次的。把这些约束摆在眼前,其实答案就很明显了:

  • 序列的遍历只能单步向前;
  • 序列表现的语义,是某种形式的值,它支持的各种访问操作应该是只读的;

如何以标准库的视角设计一个类型

接下来,我们思考第二个问题。把序列作为一个标准库的组件进行设计的时候,我们应该从哪些方面来考虑呢?其实,这个问题可以进一步放大成:设计一个容器类型应该从哪些方面进行考虑呢?实际上,得益于编程语言自身的发展,关于标准库中容器类的设计,已经被人们总结出了一些规律。围绕着容器类,一共有三个大的概念,分别是:

  • Container - 容器类型本身,它提供了元素的存储,并为各种不同容器(数组、链表、字典、树等等)的访问提供了一致的接口;
  • Iterator - 与容器搭配工作的Iterator,它为用各种不同的形式遍历容器(向前、向后、随机访问)提供了一致的接口。通常,每一个Container都有它“御用”的Iterator,因为Iterator的各种实现需要对Container的内部构造了如指掌;
  • Algorithm - 当Container和Iterator有了一致的接口之后,也就意味着对各种不同形式数据结构的访问都有了一致的访问方法,于是,我们就可以基于这些接口,来开发出重用度极高的通用算法,这些算法只基于通用接口描述的核心语义,而不与任何具体的数据结构相关;

基于上面这三个大的概念,我们可以进一步细化它们各自应该考虑的约束,也就是应该提供哪些接口:

对于Container而言,我们应该回答下面几个“它应该”的问题:

  • 暴露哪些和容器自身有关的类型;
  • 如何初始化;
  • 支持哪些赋值方式;
  • 提供哪些和尺寸有关的接口;
  • 有哪些直接访问元素的方法;
  • 可以获取哪些形式的Iterator;
  • 支持哪些形式的比较;
  • 提供哪些以只读方式访问元素的接口;
  • 提供哪些增、删、改元素的接口;

对于Iterator而言,我们应该回答下面几个“它应该”的问题:

  • 暴露哪些和Iterator自身有关的类型;
  • 提供哪些在Container中移动位置的接口;
  • 提供哪些访问Container数据成员的接口;

Sequence.swift完整源码-20200418

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

/// A type that supplies the values of a sequence one at a time.
///
/// The `IteratorProtocol` protocol is tightly linked with the `Sequence`
/// protocol. Sequences provide access to their elements by creating an
/// iterator, which keeps track of its iteration process and returns one
/// element at a time as it advances through the sequence.
///
/// Whenever you use a `for`-`in` loop with an array, set, or any other
/// collection or sequence, you're using that type's iterator. Swift uses a
/// sequence's or collection's iterator internally to enable the `for`-`in`
/// loop language construct.
///
/// Using a sequence's iterator directly gives you access to the same elements
/// in the same order as iterating over that sequence using a `for`-`in` loop.
/// For example, you might typically use a `for`-`in` loop to print each of
/// the elements in an array.
///
/// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]
/// for animal in animals {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// Behind the scenes, Swift uses the `animals` array's iterator to loop over
/// the contents of the array.
///
/// var animalIterator = animals.makeIterator()
/// while let animal = animalIterator.next() {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// The call to `animals.makeIterator()` returns an instance of the array's
/// iterator. Next, the `while` loop calls the iterator's `next()` method
/// repeatedly, binding each element that is returned to `animal` and exiting
/// when the `next()` method returns `nil`.
///
/// Using Iterators Directly
/// ========================
///
/// You rarely need to use iterators directly, because a `for`-`in` loop is the
/// more idiomatic approach to traversing a sequence in Swift. Some
/// algorithms, however, may call for direct iterator use.
///
/// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)`
/// method defined in the standard library, which takes an initial value and a
/// combining closure, `reduce1(_:)` uses the first element of the sequence as
/// the initial value.
///
/// Here's an implementation of the `reduce1(_:)` method. The sequence's
/// iterator is used directly to retrieve the initial value before looping
/// over the rest of the sequence.
///
/// extension Sequence {
/// func reduce1(
/// _ nextPartialResult: (Element, Element) -> Element
/// ) -> Element?
/// {
/// var i = makeIterator()
/// guard var accumulated = i.next() else {
/// return nil
/// }
///
/// while let element = i.next() {
/// accumulated = nextPartialResult(accumulated, element)
/// }
/// return accumulated
/// }
/// }
///
/// The `reduce1(_:)` method makes certain kinds of sequence operations
/// simpler. Here's how to find the longest string in a sequence, using the
/// `animals` array introduced earlier as an example:
///
/// let longestAnimal = animals.reduce1 { current, element in
/// if current.count > element.count {
/// return current
/// } else {
/// return element
/// }
/// }
/// print(longestAnimal)
/// // Prints "Butterfly"
///
/// Using Multiple Iterators
/// ========================
///
/// Whenever you use multiple iterators (or `for`-`in` loops) over a single
/// sequence, be sure you know that the specific sequence supports repeated
/// iteration, either because you know its concrete type or because the
/// sequence is also constrained to the `Collection` protocol.
///
/// Obtain each separate iterator from separate calls to the sequence's
/// `makeIterator()` method rather than by copying. Copying an iterator is
/// safe, but advancing one copy of an iterator by calling its `next()` method
/// may invalidate other copies of that iterator. `for`-`in` loops are safe in
/// this regard.
///
/// Adding IteratorProtocol Conformance to Your Type
/// ================================================
///
/// Implementing an iterator that conforms to `IteratorProtocol` is simple.
/// Declare a `next()` method that advances one step in the related sequence
/// and returns the current element. When the sequence has been exhausted, the
/// `next()` method returns `nil`.
///
/// For example, consider a custom `Countdown` sequence. You can initialize the
/// `Countdown` sequence with a starting integer and then iterate over the
/// count down to zero. The `Countdown` structure's definition is short: It
/// contains only the starting count and the `makeIterator()` method required
/// by the `Sequence` protocol.
///
/// struct Countdown: Sequence {
/// let start: Int
///
/// func makeIterator() -> CountdownIterator {
/// return CountdownIterator(self)
/// }
/// }
///
/// The `makeIterator()` method returns another custom type, an iterator named
/// `CountdownIterator`. The `CountdownIterator` type keeps track of both the
/// `Countdown` sequence that it's iterating and the number of times it has
/// returned a value.
///
/// struct CountdownIterator: IteratorProtocol {
/// let countdown: Countdown
/// var times = 0
///
/// init(_ countdown: Countdown) {
/// self.countdown = countdown
/// }
///
/// mutating func next() -> Int? {
/// let nextNumber = countdown.start - times
/// guard nextNumber > 0
/// else { return nil }
///
/// times += 1
/// return nextNumber
/// }
/// }
///
/// Each time the `next()` method is called on a `CountdownIterator` instance,
/// it calculates the new next value, checks to see whether it has reached
/// zero, and then returns either the number, or `nil` if the iterator is
/// finished returning elements of the sequence.
///
/// Creating and iterating over a `Countdown` sequence uses a
/// `CountdownIterator` to handle the iteration.
///
/// let threeTwoOne = Countdown(start: 3)
/// for count in threeTwoOne {
/// print("\(count)...")
/// }
/// // Prints "3..."
/// // Prints "2..."
/// // Prints "1..."
public protocol IteratorProtocol {
/// The type of element traversed by the iterator.
associatedtype Element

/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
mutating func next() -> Element?
}

/// A type that provides sequential, iterated access to its elements.
///
/// A sequence is a list of values that you can step through one at a time. The
/// most common way to iterate over the elements of a sequence is to use a
/// `for`-`in` loop:
///
/// let oneTwoThree = 1...3
/// for number in oneTwoThree {
/// print(number)
/// }
/// // Prints "1"
/// // Prints "2"
/// // Prints "3"
///
/// While seemingly simple, this capability gives you access to a large number
/// of operations that you can perform on any sequence. As an example, to
/// check whether a sequence includes a particular value, you can test each
/// value sequentially until you've found a match or reached the end of the
/// sequence. This example checks to see whether a particular insect is in an
/// array.
///
/// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// var hasMosquito = false
/// for bug in bugs {
/// if bug == "Mosquito" {
/// hasMosquito = true
/// break
/// }
/// }
/// print("'bugs' has a mosquito: \(hasMosquito)")
/// // Prints "'bugs' has a mosquito: false"
///
/// The `Sequence` protocol provides default implementations for many common
/// operations that depend on sequential access to a sequence's values. For
/// clearer, more concise code, the example above could use the array's
/// `contains(_:)` method, which every sequence inherits from `Sequence`,
/// instead of iterating manually:
///
/// if bugs.contains("Mosquito") {
/// print("Break out the bug spray.")
/// } else {
/// print("Whew, no mosquitos!")
/// }
/// // Prints "Whew, no mosquitos!"
///
/// Repeated Access
/// ===============
///
/// The `Sequence` protocol makes no requirement on conforming types regarding
/// whether they will be destructively consumed by iteration. As a
/// consequence, don't assume that multiple `for`-`in` loops on a sequence
/// will either resume iteration or restart from the beginning:
///
/// for element in sequence {
/// if ... some condition { break }
/// }
///
/// for element in sequence {
/// // No defined behavior
/// }
///
/// In this case, you cannot assume either that a sequence will be consumable
/// and will resume iteration, or that a sequence is a collection and will
/// restart iteration from the first element. A conforming sequence that is
/// not a collection is allowed to produce an arbitrary sequence of elements
/// in the second `for`-`in` loop.
///
/// To establish that a type you've created supports nondestructive iteration,
/// add conformance to the `Collection` protocol.
///
/// Conforming to the Sequence Protocol
/// ===================================
///
/// Making your own custom types conform to `Sequence` enables many useful
/// operations, like `for`-`in` looping and the `contains` method, without
/// much effort. To add `Sequence` conformance to your own custom type, add a
/// `makeIterator()` method that returns an iterator.
///
/// Alternatively, if your type can act as its own iterator, implementing the
/// requirements of the `IteratorProtocol` protocol and declaring conformance
/// to both `Sequence` and `IteratorProtocol` are sufficient.
///
/// Here's a definition of a `Countdown` sequence that serves as its own
/// iterator. The `makeIterator()` method is provided as a default
/// implementation.
///
/// struct Countdown: Sequence, IteratorProtocol {
/// var count: Int
///
/// mutating func next() -> Int? {
/// if count == 0 {
/// return nil
/// } else {
/// defer { count -= 1 }
/// return count
/// }
/// }
/// }
///
/// let threeToGo = Countdown(count: 3)
/// for i in threeToGo {
/// print(i)
/// }
/// // Prints "3"
/// // Prints "2"
/// // Prints "1"
///
/// Expected Performance
/// ====================
///
/// A sequence should provide its iterator in O(1). The `Sequence` protocol
/// makes no other requirements about element access, so routines that
/// traverse a sequence should be considered O(*n*) unless documented
/// otherwise.
public protocol Sequence {
/// A type representing the sequence's elements.
associatedtype Element

/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
associatedtype Iterator: IteratorProtocol where Iterator.Element == Element

/// A type that represents a subsequence of some of the sequence's elements.
// associatedtype SubSequence: Sequence = AnySequence<Element>
// where Element == SubSequence.Element,
// SubSequence.SubSequence == SubSequence
// typealias SubSequence = AnySequence<Element>

/// Returns an iterator over the elements of this sequence.
__consuming func makeIterator() -> Iterator

/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
var underestimatedCount: Int { get }

func _customContainsEquatableElement(
_ element: Element
) -> Bool?

/// Create a native array buffer containing the elements of `self`,
/// in the same order.
__consuming func _copyToContiguousArray() -> ContiguousArray<Element>

/// Copy `self` into an unsafe buffer, returning a partially-consumed
/// iterator with any elements that didn't fit remaining.
__consuming func _copyContents(
initializing ptr: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index)

/// Call `body(p)`, where `p` is a pointer to the collection's
/// contiguous storage. If no such storage exists, it is
/// first created. If the collection does not support an internal
/// representation in a form of contiguous storage, `body` is not
/// called and `nil` is returned.
///
/// A `Collection` that provides its own implementation of this method
/// must also guarantee that an equivalent buffer of its `SubSequence`
/// can be generated by advancing the pointer by the distance to the
/// slice's `startIndex`.
func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R?
}

// Provides a default associated type witness for Iterator when the
// Self type is both a Sequence and an Iterator.
extension Sequence where Self: IteratorProtocol {
// @_implements(Sequence, Iterator)
public typealias _Default_Iterator = Self
}

/// A default makeIterator() function for `IteratorProtocol` instances that
/// are declared to conform to `Sequence`
extension Sequence where Self.Iterator == Self {
/// Returns an iterator over the elements of this sequence.
@inlinable
public __consuming func makeIterator() -> Self {
return self
}
}

/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct DropFirstSequence<Base: Sequence> {
@usableFromInline
internal let _base: Base
@usableFromInline
internal let _limit: Int

@inlinable
public init(_ base: Base, dropping limit: Int) {
_precondition(limit >= 0,
"Can't drop a negative number of elements from a sequence")
_base = base
_limit = limit
}
}

extension DropFirstSequence: Sequence {
public typealias Element = Base.Element
public typealias Iterator = Base.Iterator
public typealias SubSequence = AnySequence<Element>

@inlinable
public __consuming func makeIterator() -> Iterator {
var it = _base.makeIterator()
var dropped = 0
while dropped < _limit, it.next() != nil { dropped &+= 1 }
return it
}

@inlinable
public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> {
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
//
// i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to
// [1,2,3,4].dropFirst(2).
return DropFirstSequence(_base, dropping: _limit + k)
}
}

/// A sequence that only consumes up to `n` elements from an underlying
/// `Base` iterator.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct PrefixSequence<Base: Sequence> {
@usableFromInline
internal var _base: Base
@usableFromInline
internal let _maxLength: Int

@inlinable
public init(_ base: Base, maxLength: Int) {
_precondition(maxLength >= 0, "Can't take a prefix of negative length")
_base = base
_maxLength = maxLength
}
}

extension PrefixSequence {
@frozen
public struct Iterator {
@usableFromInline
internal var _base: Base.Iterator
@usableFromInline
internal var _remaining: Int

@inlinable
internal init(_ base: Base.Iterator, maxLength: Int) {
_base = base
_remaining = maxLength
}
}
}

extension PrefixSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element

@inlinable
public mutating func next() -> Element? {
if _remaining != 0 {
_remaining &-= 1
return _base.next()
} else {
return nil
}
}
}

extension PrefixSequence: Sequence {
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_base.makeIterator(), maxLength: _maxLength)
}

@inlinable
public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> {
let length = Swift.min(maxLength, self._maxLength)
return PrefixSequence(_base, maxLength: length)
}
}


/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct DropWhileSequence<Base: Sequence> {
public typealias Element = Base.Element

@usableFromInline
internal var _iterator: Base.Iterator
@usableFromInline
internal var _nextElement: Element?

@inlinable
internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows {
_iterator = iterator
_nextElement = _iterator.next()

while let x = _nextElement, try predicate(x) {
_nextElement = _iterator.next()
}
}

@inlinable
internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows {
self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate)
}
}

extension DropWhileSequence {
@frozen
public struct Iterator {
@usableFromInline
internal var _iterator: Base.Iterator
@usableFromInline
internal var _nextElement: Element?

@inlinable
internal init(_ iterator: Base.Iterator, nextElement: Element?) {
_iterator = iterator
_nextElement = nextElement
}
}
}

extension DropWhileSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element

@inlinable
public mutating func next() -> Element? {
guard let next = _nextElement else { return nil }
_nextElement = _iterator.next()
return next
}
}

extension DropWhileSequence: Sequence {
@inlinable
public func makeIterator() -> Iterator {
return Iterator(_iterator, nextElement: _nextElement)
}

@inlinable
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> DropWhileSequence<Base> {
guard let x = _nextElement, try predicate(x) else { return self }
return try DropWhileSequence(iterator: _iterator, predicate: predicate)
}
}

//===----------------------------------------------------------------------===//
// Default implementations for Sequence
//===----------------------------------------------------------------------===//

extension Sequence {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)

var iterator = self.makeIterator()

// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}

/// Returns an array containing, in order, the elements of the sequence
/// that satisfy the given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter isIncluded: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `isIncluded` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}

@_transparent
public func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {

var result = ContiguousArray<Element>()

var iterator = self.makeIterator()

while let element = iterator.next() {
if try isIncluded(element) {
result.append(element)
}
}

return Array(result)
}

/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
@inlinable
public var underestimatedCount: Int {
return 0
}

@inlinable
@inline(__always)
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return nil
}

/// Calls the given closure on each element in the sequence in the same order
/// as a `for`-`in` loop.
///
/// The two loops in the following example produce the same output:
///
/// let numberWords = ["one", "two", "three"]
/// for word in numberWords {
/// print(word)
/// }
/// // Prints "one"
/// // Prints "two"
/// // Prints "three"
///
/// numberWords.forEach { word in
/// print(word)
/// }
/// // Same as above
///
/// Using the `forEach` method is distinct from a `for`-`in` loop in two
/// important ways:
///
/// 1. You cannot use a `break` or `continue` statement to exit the current
/// call of the `body` closure or skip subsequent calls.
/// 2. Using the `return` statement in the `body` closure will exit only from
/// the current call to `body`, not from any outer scope, and won't skip
/// subsequent calls.
///
/// - Parameter body: A closure that takes an element of the sequence as a
/// parameter.
@_semantics("sequence.forEach")
@inlinable
public func forEach(
_ body: (Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}

extension Sequence {
/// Returns the first element of the sequence that satisfies the given
/// predicate.
///
/// The following example uses the `first(where:)` method to find the first
/// negative number in an array of integers:
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// if let firstNegative = numbers.first(where: { $0 < 0 }) {
/// print("The first negative number is \(firstNegative).")
/// }
/// // Prints "The first negative number is -2."
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element is a match.
/// - Returns: The first element of the sequence that satisfies `predicate`,
/// or `nil` if there is no element that satisfies `predicate`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func first(
where predicate: (Element) throws -> Bool
) rethrows -> Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}

extension Sequence where Element: Equatable {
/// Returns the longest possible subsequences of the sequence, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " ")
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1)
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false)
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the sequence and for each instance of `separator` at the
/// start or end of the sequence. If `true`, only nonempty subsequences
/// are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [ArraySlice<Element>] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}

extension Sequence {

/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(
/// line.split(maxSplits: 1, whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `true` for the `allowEmptySlices` parameter, so
/// the returned array contains empty strings where spaces were repeated.
///
/// print(
/// line.split(
/// omittingEmptySubsequences: false,
/// whereSeparator: { $0 == " " }
/// ).map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` predicate.
/// If `true`, only nonempty subsequences are returned. The default
/// value is `true`.
/// - isSeparator: A closure that returns `true` if its argument should be
/// used to split the sequence; otherwise, `false`.
/// - Returns: An array of subsequences, split from this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [ArraySlice<Element>] {
_precondition(maxSplits >= 0, "Must take zero or more splits")
let whole = Array(self)
return try whole.split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: isSeparator)
}

/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the sequence.
///
/// The sequence must be finite. If the maximum length exceeds the number of
/// elements in the sequence, the result contains all the elements in the
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func suffix(_ maxLength: Int) -> [Element] {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
guard maxLength != 0 else { return [] }

// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements into a ring buffer to save space. Once all
// elements are consumed, reorder the ring buffer into a copy and return it.
// This saves memory for sequences particularly longer than `maxLength`.
var ringBuffer = ContiguousArray<Element>()
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))

var i = 0

for element in self {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i = (i + 1) % maxLength
}
}

if i != ringBuffer.startIndex {
var rotated = ContiguousArray<Element>()
rotated.reserveCapacity(ringBuffer.count)
rotated += ringBuffer[i..<ringBuffer.endIndex]
rotated += ringBuffer[0..<i]
return Array(rotated)
} else {
return Array(ringBuffer)
}
}

/// Returns a sequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the sequence, the result is an empty sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter k: The number of elements to drop from the beginning of
/// the sequence. `k` must be greater than or equal to zero.
/// - Returns: A sequence starting after the specified number of
/// elements.
///
/// - Complexity: O(1), with O(*k*) deferred to each iteration of the result,
/// where *k* is the number of elements to drop from the beginning of
/// the sequence.
@inlinable
public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> {
return DropFirstSequence(self, dropping: k)
}

/// Returns a sequence containing all but the given number of final
/// elements.
///
/// The sequence must be finite. If the number of elements to drop exceeds
/// the number of elements in the sequence, the result is an empty
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// sequence. `n` must be greater than or equal to zero.
/// - Returns: A sequence leaving off the specified number of elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func dropLast(_ k: Int = 1) -> [Element] {
_precondition(k >= 0, "Can't drop a negative number of elements from a sequence")
guard k != 0 else { return Array(self) }

// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements from this sequence in a holding tank, a ring buffer
// of size <= k. If more elements keep coming in, pull them out of the
// holding tank into the result, an `Array`. This saves
// `k` * sizeof(Element) of memory, because slices keep the entire
// memory of an `Array` alive.
var result = ContiguousArray<Element>()
var ringBuffer = ContiguousArray<Element>()
var i = ringBuffer.startIndex

for element in self {
if ringBuffer.count < k {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = (i + 1) % k
}
}
return Array(result)
}

/// Returns a sequence by skipping the initial, consecutive elements that
/// satisfy the given predicate.
///
/// The following example uses the `drop(while:)` method to skip over the
/// positive numbers at the beginning of the `numbers` array. The result
/// begins with the first element of `numbers` that does not satisfy
/// `predicate`.
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// let startingWithNegative = numbers.drop(while: { $0 > 0 })
/// // startingWithNegative == [-2, 9, -6, 10, 1]
///
/// If `predicate` matches every element in the sequence, the result is an
/// empty sequence.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element should be included in the result.
/// - Returns: A sequence starting after the initial, consecutive elements
/// that satisfy `predicate`.
///
/// - Complexity: O(*k*), where *k* is the number of elements to drop from
/// the beginning of the sequence.
@inlinable
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> DropWhileSequence<Self> {
return try DropWhileSequence(self, predicate: predicate)
}

/// Returns a sequence, up to the specified maximum length, containing the
/// initial elements of the sequence.
///
/// If the maximum length exceeds the number of elements in the sequence,
/// the result contains all the elements in the sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A sequence starting at the beginning of this sequence
/// with at most `maxLength` elements.
///
/// - Complexity: O(1)
@inlinable
public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> {
return PrefixSequence(self, maxLength: maxLength)
}

/// Returns a sequence containing the initial, consecutive elements that
/// satisfy the given predicate.
///
/// The following example uses the `prefix(while:)` method to find the
/// positive numbers at the beginning of the `numbers` array. Every element
/// of `numbers` up to, but not including, the first negative value is
/// included in the result.
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// let positivePrefix = numbers.prefix(while: { $0 > 0 })
/// // positivePrefix == [3, 7, 4]
///
/// If `predicate` matches every element in the sequence, the resulting
/// sequence contains every element of the sequence.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element should be included in the result.
/// - Returns: A sequence of the initial, consecutive elements that
/// satisfy `predicate`.
///
/// - Complexity: O(*k*), where *k* is the length of the result.
@inlinable
public __consuming func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()

for element in self {
guard try predicate(element) else {
break
}
result.append(element)
}
return Array(result)
}
}

extension Sequence {
/// Copies `self` into the supplied buffer.
///
/// - Precondition: The memory in `self` is uninitialized. The buffer must
/// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`.
///
/// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are
/// initialized.
@inlinable
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
var it = self.makeIterator()
guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) }
for idx in buffer.startIndex..<buffer.count {
guard let x = it.next() else {
return (it, idx)
}
ptr.initialize(to: x)
ptr += 1
}
return (it,buffer.endIndex)
}

@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
}

// FIXME(ABI)#182
// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,
// pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness"
/// A sequence built around an iterator of type `Base`.
///
/// Useful mostly to recover the ability to use `for`...`in`,
/// given just an iterator `i`:
///
/// for x in IteratorSequence(i) { ... }
@frozen
public struct IteratorSequence<Base: IteratorProtocol> {
@usableFromInline
internal var _base: Base

/// Creates an instance whose iterator is a copy of `base`.
@inlinable
public init(_ base: Base) {
_base = base
}
}

extension IteratorSequence: IteratorProtocol, Sequence {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable
public mutating func next() -> Base.Element? {
return _base.next()
}
}

/* FIXME: ideally for compatability we would declare
extension Sequence {
@available(swift, deprecated: 5, message: "")
public typealias SubSequence = AnySequence<Element>
}
*/


CATALOG
  1. 1. Swift标准库源码
    1. 1.1. 如何阅读 Swift 标准库中的源码 | Swift源码地址
      1. 1.1.1. 00关键词
      2. 1.1.2. Algorithm源码
        1. 1.1.2.1. min()
        2. 1.1.2.2. max()
        3. 1.1.2.3. EnumeratedSequence
      3. 1.1.3. Sequence源码
        1. 1.1.3.1. IteratorProtocol
        2. 1.1.3.2. Sequence
      4. 1.1.4. Sequence实现
        1. 1.1.4.1. map()
        2. 1.1.4.2. filter()
        3. 1.1.4.3. forEach()
        4. 1.1.4.4. split()
        5. 1.1.4.5. IteratorSequence()
      5. 1.1.5.
      6. 1.1.6.
      7. 1.1.7.
      8. 1.1.8.
      9. 1.1.9.
      10. 1.1.10. SequenceAlgorithms源码
        1. 1.1.10.1. enumerated()
        2. 1.1.10.2. min()
        3. 1.1.10.3. max()
        4. 1.1.10.4. contains()
        5. 1.1.10.5. reduce()函数
        6. 1.1.10.6. reversed()
        7. 1.1.10.7. flatMap()
      11. 1.1.11. 03 zip源码
        1. 1.1.11.1. zip使用
        2. 1.1.11.2. zip源码
        3. 1.1.11.3. 04
        4. 1.1.11.4. 05
        5. 1.1.11.5. 06
        6. 1.1.11.6. 07
        7. 1.1.11.7. 08
        8. 1.1.11.8. 09
        9. 1.1.11.9. 10
    2. 1.2. Sequence是一个值类型
    3. 1.3. 如何以标准库的视角设计一个类型
    4. 1.4. Sequence.swift完整源码-20200418