Skip to content

Commit 5570a71

Browse files
committed
Add two examples of Sequence methods gained through the conformance to Collection protocol.
1 parent f567885 commit 5570a71

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

Linked List/LinkedList.playground/Contents.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,4 +453,16 @@ let collection: LinkedList<Int> = [1, 2, 3, 4, 5]
453453
let index2 = collection.index(collection.startIndex, offsetBy: 2)
454454
let value = collection[index2] // 3
455455

456+
// Iterating in a for loop, since the Sequence protocol allows this.
457+
var sum = 0
458+
for element in collection {
459+
sum += element
460+
}
461+
// sum is 15
462+
463+
// Another way of achieving the same result though 'reduce', another method defined in an extension of Sequence. Collections are Sequences.
464+
let result = collection.reduce(0) {$0 + $1} // 15
465+
466+
467+
456468

0 commit comments

Comments
 (0)