Skip to content

Instantly share code, notes, and snippets.

@hollance
Created June 23, 2014 16:05
Show Gist options
  • Select an option

  • Save hollance/f9b74e72dc65a15a3022 to your computer and use it in GitHub Desktop.

Select an option

Save hollance/f9b74e72dc65a15a3022 to your computer and use it in GitHub Desktop.
Very basic set in Swift
class Set<T: Hashable>: Sequence, Printable {
var dictionary = Dictionary<T, Bool>() // private
func addElement(newElement: T) {
dictionary[newElement] = true
}
func removeElement(element: T) {
dictionary[element] = nil
}
func containsElement(element: T) -> Bool {
return dictionary[element] != nil
}
func allElements() -> T[] {
return Array(dictionary.keys)
}
var count: Int {
return dictionary.count
}
func unionSet(otherSet: Set<T>) -> Set<T> {
var combined = Set<T>()
for obj in dictionary.keys {
combined.dictionary[obj] = true
}
for obj in otherSet.dictionary.keys {
combined.dictionary[obj] = true
}
return combined
}
func generate() -> IndexingGenerator<Array<T>> {
return allElements().generate()
}
var description: String {
return dictionary.description
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment