Skip to content

Instantly share code, notes, and snippets.

@DandyLyons
Created October 30, 2024 00:22
Show Gist options
  • Select an option

  • Save DandyLyons/8ab7e104c25a9ed3d3a58967de1fb037 to your computer and use it in GitHub Desktop.

Select an option

Save DandyLyons/8ab7e104c25a9ed3d3a58967de1fb037 to your computer and use it in GitHub Desktop.
Unordered Equality Checking in Swift
extension Sequence where Element: Hashable {
/// Count the number of occurrences of each value in a sequence
public func countFrequency() -> [Element: Int] {
var result = [Element: Int]()
for element in self {
result[element, default: 0] += 1
}
return result
}
/// Check for sequence equality while ignoring order
public func hasSameElements(as s2: Self) -> Bool {
let freq1 = self.countFrequency()
let freq2 = s2.countFrequency()
return freq1 == freq2
}
}
extension Collection where Element: Hashable {
/// Check for collection equality while ignoring order
public func hasSameElements(as c2: Self) -> Bool {
guard self.count == c2.count else { return false }
let freq1 = self.countFrequency()
let freq2 = c2.countFrequency()
return freq1 == freq2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment