```
extension DistinctPrimeFactorizationSequence.Iterator: IteratorProtocol {
public mutating func next() -> Set<Integer>? {
defer { upcoming += 1 }
// Check if we got a prime or not.
var primeLink = taggedComposites.removeValue(forKey: upcoming)
if primeLink == nil {
// We did get a new prime!
primeCallback?(upcoming)
primeLink = Prime(prime: upcoming)
}
// (Otherwise,) move all the factors to their next multiples.
var primeFactors = Set<Integer>(minimumCapacity: 2)
while var hardPrime = primeLink {
// Lock the results.
let prime = hardPrime.value
primeFactors.update(with: prime)
// Re-do prime connections
primeLink = primeLink?.next
if !isKnownUniquelyReferenced(&hardPrime) {
// Do copy-on-write
hardPrime = Prime(prime: prime)
}
hardPrime.next = nil
// Do composite connections
let nextUpcoming = upcoming + prime
hardPrime.next = taggedComposites[nextUpcoming]
taggedComposites[nextUpcoming] = hardPrime
}
return primeFactors
}
}
```

`upcoming`

is of `Integer`

, a generic `BinaryInteger`

type. `taggedComposites`

is a `[Integer: Prime]`

, where `Prime`

is a `final class`

with an `Integer`

value and an `Optional`

link to the next node, as a crappy linked list.

In the middle section of the `while`

loop, am I doing that right? I move `primeLink`

to the next node to ensure `hardPrime`

is the last reference, unless I value-copied the iterator object out-of-band. Then I clone `hardPrime`

if needed and cut off its link to its original down-node.

The last part of the `while`

loop is right too? It should work whether to establish `hardPrime`

as the sole `Prime`

node for a new dictionary entry or to insert it as the head node to an existing entry.

(I originally had a `[Integer: Set<Integer>]`

, then I worried about the prime tags going across by value, which probably makes new `Set`

-internal nodes, copies the values, then removes the old ones. Moving to a `class`

directly lets me directly transfer nodes across dictionary entries, only creating new ones when I find a new prime number (or do a COW cloning).)