Created
June 4, 2021 15:09
-
-
Save andr3a88/69e79834b060968aaf59a15138ea573e to your computer and use it in GitHub Desktop.
Combine A custom publisher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Combine | |
extension Publisher{ | |
func isPrimeInteger<T: BinaryInteger>() -> Publishers | |
.CompactMap<Self, T> where Output == T { | |
compactMap{self.isPrime($0)} | |
} | |
func isPrime<T: BinaryInteger>(_ n: T) -> T? { | |
guard n != 2 else { return n } | |
guard n % 2 != 0 && n > 1 else { return nil } | |
var i = 3 | |
while i * i <= n { | |
if (Int(n) % i) == 0 { | |
return nil | |
} | |
i += 2 | |
} | |
return n | |
} | |
} | |
let numbers:[Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
numbers | |
.publisher | |
.isPrimeInteger() | |
.sink { print($0) } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment