Created
January 7, 2018 22:26
-
-
Save JadenGeller/b58d87ecc4f0dbdf1a4b81d62cf10918 to your computer and use it in GitHub Desktop.
TypeDictionary
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
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