You can make your data structures iteratable. Here’s an example from https://holyswift.app/linked-lists-with-sequence-and-iteratorprotocol-in-swift . This is just one example of how swift’s expressiveness can help you make functional code.
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
|
class LinkedList: Sequence {
var root: LinkedListNode?
func makeIterator() -> LinkedListIterator {
return LinkedListIterator(start: root)
}
}
class LinkedListIterator: IteratorProtocol { // Mark 1
var current: LinkedListNode?
init(start: LinkedListNode?) {
current = start
}
func next() -> LinkedListNode? { // Mark 2
let actual = current
current = current?.next
return actual
}
}
let list = LinkedList()
let first = LinkedListNode(value: 1)
let second = LinkedListNode(value: 2)
let third = LinkedListNode(value: 3)
list.root = first
first.next = second
second.next = third
for node in list {
dump(node.value)
}
|
Originally published 09/21/2021 @ https://pittcsc.org/ Discord
Published here on 09/09/2022. Blog published date reflects the original date of publication.