How do I implement a generic bloom filter in Swift?

A Bloom Filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. False positives are possible, but false negatives are not. In this example, we'll implement a generic Bloom Filter in Swift.

Generic Bloom Filter Implementation in Swift

import Foundation struct BloomFilter { private var bitArray: [Bool] private let size: Int private let hashFunctions: [(T) -> Int] init(size: Int, hashFunctions: [(T) -> Int]) { self.size = size self.bitArray = Array(repeating: false, count: size) self.hashFunctions = hashFunctions } mutating func insert(_ item: T) { for hashFunction in hashFunctions { let index = hashFunction(item) % size bitArray[index] = true } } func contains(_ item: T) -> Bool { for hashFunction in hashFunctions { let index = hashFunction(item) % size if !bitArray[index] { return false } } return true } } // Example hash functions func hash1(_ input: String) -> Int { return input.hashValue } func hash2(_ input: String) -> Int { return (input.hashValue * 2) % 100 } // Using the Bloom Filter var bloomFilter = BloomFilter(size: 100, hashFunctions: [hash1, hash2]) bloomFilter.insert("Hello") print(bloomFilter.contains("Hello")) // true print(bloomFilter.contains("World")) // false

Bloom Filter Swift Generic Data Structures Probabilistic Data Structures