Created
October 31, 2016 08:30
-
-
Save robnadin/750823507b8b2ef49cd943af411eb820 to your computer and use it in GitHub Desktop.
A generic wrapper for NSHashTable on Swift <= 2.3
This file contains 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
import Foundation | |
#if swift(>=3.0) | |
typealias HashTable<ObjectType: AnyObject> = NSHashTable<ObjectType> | |
#else | |
struct HashTable<ObjectType: AnyObject> { | |
private let _table = NSHashTable.weakObjectsHashTable() | |
static func weakObjects() -> HashTable<ObjectType> { | |
return HashTable<ObjectType>() | |
} | |
var count: Int { | |
return _table.count | |
} | |
func member(object: ObjectType?) -> ObjectType? { | |
return _table.member(object) as? ObjectType | |
} | |
func add(object: ObjectType?) { | |
_table.addObject(object) | |
} | |
func remove(object: ObjectType?) { | |
_table.removeObject(object) | |
} | |
func removeAllObjects() { | |
_table.removeAllObjects() | |
} | |
var allObjects: [ObjectType] { | |
return unsafeBitCast(_table.allObjects, [ObjectType].self) | |
} | |
var anyObject: ObjectType? { | |
return _table.anyObject as? ObjectType | |
} | |
func contains(object: ObjectType?) -> Bool { | |
return _table.containsObject(object) | |
} | |
} | |
extension HashTable: SequenceType { | |
func generate() -> NSFastGenerator { | |
return _table.objectEnumerator().generate() | |
} | |
} | |
extension HashTable: CustomStringConvertible { | |
var description: String { | |
var string = "\(self.dynamicType) {\n" | |
_table.allObjects.enumerate().forEach { idx, obj in | |
string += "[\(idx)] \(obj)\n" | |
} | |
string += "}" | |
return string | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment