Skip to content

Instantly share code, notes, and snippets.

@jjbubudi
Created September 6, 2016 21:25
Show Gist options
  • Save jjbubudi/d35eed3239f3091e9a1e24da375ee971 to your computer and use it in GitHub Desktop.
Save jjbubudi/d35eed3239f3091e9a1e24da375ee971 to your computer and use it in GitHub Desktop.
Typed Dictionary in Swift
public struct Key<T> {
let id: String
private let type: T.Type = T.self
}
extension Key: Hashable {
public var hashValue: Int {
get {
return self.id.hashValue ^ "\(self.type)".hashValue
}
}
}
public func ==<T>(key1: Key<T>, key2: Key<T>) -> Bool {
return key1.id == key2.id && key1.type == key2.type
}
public struct TypedDictionary {
private var dictionary: [Int: Any] = [:]
public mutating func put<T>(key: Key<T>, value: T) {
dictionary[key.hashValue] = value
}
public func get<T>(key: Key<T>) -> T? {
return dictionary[key.hashValue] as? T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment