Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created January 7, 2018 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/b58d87ecc4f0dbdf1a4b81d62cf10918 to your computer and use it in GitHub Desktop.
Save JadenGeller/b58d87ecc4f0dbdf1a4b81d62cf10918 to your computer and use it in GitHub Desktop.
TypeDictionary
private struct TypeDescriptor: Hashable, CustomStringConvertible {
private let type: Any.Type
internal init(_ type: Any.Type) {
self.type = type
}
public var hashValue: Int {
return String(describing: type).hashValue
}
public static func ==(lhs: TypeDescriptor, rhs: TypeDescriptor) -> Bool {
return lhs.type == rhs.type
}
public var description: String {
return String(describing: type)
}
}
public struct TypeDictionary: ExpressibleByArrayLiteral, CustomStringConvertible {
private var backing: [TypeDescriptor : Any] = [:]
public mutating func insert(_ value: Any) {
self.backing[TypeDescriptor(type(of: value))] = value
}
public subscript(type: Any.Type) -> Any? {
return self.backing[TypeDescriptor(type)]
}
public subscript<T>(type: T.Type) -> T? {
get {
guard let value = backing[TypeDescriptor(type)] else { return nil }
return (value as! T)
}
set {
guard let newValue = newValue else {
backing[TypeDescriptor(type)] = nil
return
}
backing[TypeDescriptor(type)] = newValue
}
}
public init(arrayLiteral: Any...) {
for value in arrayLiteral {
self.insert(value)
}
}
public var description: String {
return self.backing.description
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment