Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.