Created
June 23, 2014 16:05
-
-
Save hollance/f9b74e72dc65a15a3022 to your computer and use it in GitHub Desktop.
Very basic set in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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