Creating a Set of Pairs

Is it possible to create a set of pairs along the lines of `var visited: Set<(Int, Int)> = ` without using a struct for (Int, Int) ?

The order of elements is not important and I’m exploring an alternative to `var visited = Array(repeating: Array(repeating: false, count: cols), count: rows)`

No.

let visited: Set = {
  @Pack var a = (1, 2)
  @Pack var b = (3, 4)
  return [$a, $b]
} ()

#expect(visited == Set([(1, 2), (3, 4)].map(Pack.init)))
@propertyWrapper public struct Pack<each Element> {
  public init(wrappedValue: (repeat each Element)) {
    self.wrappedValue = wrappedValue
  }

  public init(projectedValue: Self) { self = projectedValue }

  public var wrappedValue: (repeat each Element)
  public var projectedValue: Self { self }
}


// MARK: - Equatable
extension Pack: Equatable where repeat each Element: Equatable {
  public static func == (pack0: Self, pack1: Self) -> Bool {
    for elements in repeat (each pack0.wrappedValue, each pack1.wrappedValue) {
      guard elements.0 == elements.1 else { return false }
    }
    return true
  }
}

// MARK: - Hashable
extension Pack: Hashable where repeat each Element: Hashable {
  public func hash(into hasher: inout Hasher) {
    repeat hasher.combine(each wrappedValue)
  }
}

2 Likes