Unbounded Sieve of Eratosthenes in Swift
1 is not a prime number!

By definition, a prime number is an integer greater than one which has
no (positive) divisor other than 1 and itself.

Both the UnboundedSieve
iterator and the sieveOfEratosthenes function – correctly – produce 2 as the first prime. But then in PrimeSequence, the number 1
is inserted and I see no reason to do so.



From the description and naming of the max parameter in the  

/// Construct a sequence of primes up to a max.
/// ...
public init(max: Int)


constructor I would assume that it produces a sequence of all primes
up to and including max, but that is not true: It produces all
primes below max because

private func sieveOfEratosthenes(n: Int) -&gt; [Int] 


returns all primes below n. That might be unexpected. I would 
suggest to change the function so that the upper limit is included,
and give the parameters a more descriptive name:

/// Creates a sequence of primes up to (and including) `limit`.
public init(upTo limit: Int) {




I don't see the benefit of the terms parameter in

public init(terms: Int? = nil)


because  PrimeSequence(terms: numberOfTerms)
can be replaced by PrimeSequence().prefix(numberOfTerms),
using the prefix() method from the Swift standard library.
I would suggest to remove that parameter. 

That leaves us with only two cases: creating a finite sequence
(using the sieve of Eratosthenes), or an infinite sequence
(using a priority queue), and the PrimeSequence definition
can be simplified to

public struct PrimeSequence: Sequence {
    private let iterator: AnyIterator&lt;Int&gt;

    /// Creates a sequence of primes up to (and including) `limit`.
    public init(upTo limit: Int) {
        self.iterator = AnyIterator(sieveOfEratosthenes(upTo: limit).makeIterator())
   }

    /// Creates an "infinite" sequence of prime numbers.
    public init() {
        self.iterator = AnyIterator(UnboundedSieve())
    }

    public func makeIterator() -&gt; AnyIterator&lt;Int&gt; {
        return iterator
    }
}




struct UnboundedSieve looks like a clean implementation of the
priority queue-based algorithm from https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf to me. However,

sieve.enqueue(PrimeCounter(prime: counter, composite: counter + counter))


can be improved to

sieve.enqueue(PrimeCounter(prime: counter, composite: counter * counter))


since all primes less than counter have already been found.
This reduced the execution time of my test (code below) from
2.26 sec to 1.17 sec.

A possible further improvement is to treat the only even prime 2
separately and then handle only odd numbers:

private struct UnboundedSieve: IteratorProtocol {

    var sieve: PriorityQueue&lt;PrimeCounter&gt;
    var counter = 2

    init() {
        sieve = PriorityQueue { $0.composite &lt; $1.composite }
    }

    private struct PrimeCounter {
        let prime: Int
        var composite: Int
        func next() -&gt; PrimeCounter {
            return PrimeCounter(prime: prime, composite: composite + 2 * prime)
        }
    }

    mutating func next() -&gt; Int? {
        if counter == 2 {
            counter = 3
            return 2
        }

        while let catcher = sieve.peek(), catcher.composite == counter {
            while let catcher = sieve.peek(), catcher.composite == counter {
                sieve.replaceTop(with: catcher.next())
            }
            counter += 2
        }
        defer {
            sieve.enqueue(PrimeCounter(prime: counter, composite: counter * counter))
            counter += 2
        }
        return counter
    }
}


The reduced the execution time of the test code to 0.58 sec.



In sieveOfEratosthenes() the same improvement as mentioned above
applies: If a prime number is found then "crossing out multiples"
can start at the square of that prime:

private func sieveOfEratosthenes(upTo n: Int) -&gt; [Int] {
    var numbers = [Int](2...n)
    for i in 0...n-2 {
        let prime = numbers[i]
        guard prime &gt; 0 else { continue }
        for multiple in stride(from: prime * prime-2, through: n-2, by: prime) {
            numbers[multiple] = 0
        }
    }
    return numbers.filter { $0 &gt; 0 }
}


The reduced the execution time for my test code from 
0.37 sec to 0.28 sec.

The numbers array in this function holds redundant information,
memory can be saved by replacing it a by an array of booleans
which marks all numbers which have been found to be composite:

private func sieveOfEratosthenes(upTo n: Int) -&gt; [Int] {
    var result = [Int]()
    var composite = [Bool](repeating: false, count: n + 1)
    for i in 2...n {
        if !composite[i] {
            result.append(i)
            for multiple in stride(from: i * i, through: n, by: i) {
                composite[multiple] = true
            }
        }
    }
    return result
}


In my test this also turned out to be faster: 0.13 sec.



You could also implement the Eratosthenes sieve as an iterator,
which makes it non-eager and removes the results array:

private struct EratosthenesIterator: IteratorProtocol {
    let n: Int
    var composite: [Bool]
    var current = 2

    init(upTo n: Int) {
        self.n = n
        self.composite = [Bool](repeating: false, count: n + 1)
    }

    mutating func next() -&gt; Int? {
        while current &lt;= self.n {
            if !composite[current] {
                let prime = current
                for multiple in stride(from: current * current, through: self.n, by: current) {
                    composite[multiple] = true
                }
                current += 1
                return prime
            }
            current += 1
        }
        return nil
    }
}


The corresponding init method in struct PrimeSequence then becomes

    /// Creates a sequence of primes up to (and including) `limit`.
    public init(upTo limit: Int) {
        self.iterator = AnyIterator(EratosthenesIterator(upTo: limit))
   }


The execution time for the test code is now 0.12 sec.



Benchmarking code for the infinite generator:

Calculate the sum of the first 10,000 primes:

let numPrimes = 10_000
do {
    let startTime = Date()
    let sum = PrimeSequence().prefix(numPrimes).reduce(0, combine: +)
    let endTime = Date()
    print(sum, endTime.timeIntervalSince(startTime), "sec")
}


Benchmarking code for the Eratosthenes generator:

Calculates the sum of all primes below 10,000,000:

let N = 10_000_000

do {
    let startTime = Date()
    let sum = PrimeSequence(upTo: N).reduce(0, combine: +)
    let endTime = Date()
    print(sum, endTime.timeIntervalSince(startTime))
}


The tests were done on a MacBook, with the program compiled in Release mode.