How do I implement a bloom filter in Swift?

This article provides an implementation of a Bloom Filter in Swift, a space-efficient probabilistic data structure used to test whether an element is a member of a set.
Bloom Filter, Swift, Data Structures, Probabilistic Data Structure, Membership Testing
// Swift implementation of a Bloom Filter import Foundation class BloomFilter { private var bitArray: [Bool] private let size: Int private let hashFunctions: [(String) -> Int] init(size: Int, hashFunctions: [(String) -> Int]) { self.size = size self.bitArray = Array(repeating: false, count: size) self.hashFunctions = hashFunctions } func add(_ element: String) { for hashFunc in hashFunctions { let index = hashFunc(element) % size bitArray[index] = true } } func contains(_ element: String) -> Bool { for hashFunc in hashFunctions { let index = hashFunc(element) % size if !bitArray[index] { return false } } return true } } // Example hash functions func simpleHash(_ input: String) -> Int { return input.reduce(0) { $0 + Int($1.asciiValue ?? 0) } } func alternativeHash(_ input: String) -> Int { return input.reduce(1) { $0 * Int($1.asciiValue ?? 0) } } // Usage let bloomFilter = BloomFilter(size: 1000, hashFunctions: [simpleHash, alternativeHash]) bloomFilter.add("example@example.com") print(bloomFilter.contains("example@example.com")) // true print(bloomFilter.contains("test@test.com")) // false (probabilistically)

Bloom Filter Swift Data Structures Probabilistic Data Structure Membership Testing