Created
September 6, 2016 21:25
-
-
Save jjbubudi/d35eed3239f3091e9a1e24da375ee971 to your computer and use it in GitHub Desktop.
Typed Dictionary in Swift
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
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